Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(wecom): 完善 IM 接入与群通知边界

davidd856672e949c
diff --git a/apps/desktop/src/main/__tests__/notificationService.test.ts b/apps/desktop/src/main/__tests__/notificationService.test.ts
index c2d6db7431..dc91ab8abc 100644
--- a/apps/desktop/src/main/__tests__/notificationService.test.ts
+++ b/apps/desktop/src/main/__tests__/notificationService.test.ts
@@ -104,7 +104,9 @@ vi.mock('../device-link', () => ({
// mobile 正文素材:最近一条 assistant 内容(真实实现走 localDb)。默认空 = 无摘要,
// 既有用例的调用断言不带 detail;内容用例单独 mockResolvedValueOnce。
-const latestMessageText = vi.fn(async (_sessionId: string, _role: string) => '');
+const latestMessageText = vi.fn<
+ (sessionId: string, role: string) => Promise<string>
+>(async () => '');
vi.mock('../localDb/latestMessageText', () => ({
latestMessageText: (sessionId: string, role: string) => latestMessageText(sessionId, role),
}));
@@ -158,11 +160,6 @@ const baseDeps = (feishuIm: FakeFeishuIM) => ({
>[0]['feishuIm'],
});
-const withWecomGroup = (feishuIm: FakeFeishuIM, publishMarkdown: ReturnType<typeof vi.fn>) => ({
- ...baseDeps(feishuIm),
- wecomGroupPublisher: { publishMarkdown },
-});
-
describe('notificationService — channels 分发', () => {
beforeEach(() => {
// 每个用例重新注册 handler,避免相互污染。
@@ -197,24 +194,6 @@ describe('notificationService — channels 分发', () => {
expect(sendMobileSessionNotify).not.toHaveBeenCalled();
});
- it('企微群通知失败不影响其它通知通道', async () => {
- const { initNotificationService } = await freshService();
- const publishMarkdown = vi.fn(async () => Promise.reject(new Error('webhook failed')));
- initNotificationService(withWecomGroup(makeFeishuIm('ou_owner'), publishMarkdown));
-
- await expect(
- invokeHandler({
- sessionId: 's-wecom',
- title: 'Group',
- kind: 'done',
- channels: { desktop: false, wecomGroup: true },
- }),
- ).resolves.toBeUndefined();
-
- expect(publishMarkdown).toHaveBeenCalledWith(expect.stringContaining('Group'));
- expect(markSessionNeedsAttention).toHaveBeenCalledWith('s-wecom');
- });
-
it('payload 运行时校验:非法 kind / 超长 title / 空 sessionId 直接 reject,不进任何通道', async () => {
const { initNotificationService } = await freshService();
const feishuIm = makeFeishuIm('ou_owner');
diff --git a/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts b/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts
index a2d67a2250..97ea48fb59 100644
--- a/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts
+++ b/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts
@@ -29,16 +29,21 @@ function response(body: unknown, status = 200): Response {
});
}
-function createSecrets(initial: string | null = null) {
- let value = initial;
+const WEBHOOK_SECRET_NAME = 'wecom-group-webhook-url';
+const ENABLED_SETTING_NAME = 'wecom-group-notification-enabled';
+
+function createSecrets(initialUrl: string | null = null, initialEnabled: string | null = null) {
+ const values = new Map<string, string>();
+ if (initialUrl !== null) values.set(WEBHOOK_SECRET_NAME, initialUrl);
+ if (initialEnabled !== null) values.set(ENABLED_SETTING_NAME, initialEnabled);
return {
- read: vi.fn(() => value),
- write: vi.fn((_name: string, next: string) => {
- value = next;
+ read: vi.fn((name: string) => values.get(name) ?? null),
+ write: vi.fn((name: string, next: string) => {
+ values.set(name, next);
return true;
}),
- remove: vi.fn(() => {
- value = null;
+ remove: vi.fn((name: string) => {
+ values.delete(name);
}),
};
}
@@ -70,21 +75,67 @@ describe('WeCom group notification security boundary', () => {
});
it('tests before persisting and never exposes the stored URL', async () => {
- const fetchImpl = vi.fn(async () => response({ errcode: 0, errmsg: 'ok' }));
+ let sentBody = '';
+ const fetchImpl = vi.fn(async (_url: string, init: RequestInit) => {
+ sentBody = String(init.body);
+ return response({ errcode: 0, errmsg: 'ok' });
+ });
const secrets = createSecrets();
const service = new WecomGroupNotificationService(fetchImpl, secrets);
const state = await service.saveAndTest(
'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abcdefgh',
+ 'Localized test message',
);
expect(fetchImpl).toHaveBeenCalledWith(
'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abcdefgh',
expect.objectContaining({ method: 'POST', redirect: 'manual' }),
);
- expect(secrets.write).toHaveBeenCalledOnce();
- expect(state).toEqual({ configured: true, maskedKey: '••••efgh' });
+ expect(secrets.write).toHaveBeenCalledTimes(2);
+ expect(secrets.write).toHaveBeenNthCalledWith(1, WEBHOOK_SECRET_NAME, expect.any(String));
+ expect(secrets.write).toHaveBeenNthCalledWith(2, ENABLED_SETTING_NAME, 'true');
+ expect(state).toEqual({ configured: true, enabled: true, maskedKey: '••••efgh' });
expect(JSON.stringify(service.getState())).not.toContain('abcdefgh');
+ expect(sentBody).toContain('Localized test message');
+ });
+
+ it('keeps existing webhook configurations enabled until the user turns them off', () => {
+ const url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abcdefgh';
+ const service = new WecomGroupNotificationService(vi.fn(), createSecrets(url));
+
+ expect(service.getState()).toEqual({
+ configured: true,
+ enabled: true,
+ maskedKey: '••••efgh',
+ });
+ });
+
+ it('uses the persisted master switch to gate automation publishes', async () => {
+ const fetchImpl = vi.fn(async () => response({ errcode: 0, errmsg: 'ok' }));
+ const url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abcdefgh';
+ const secrets = createSecrets(url);
+ const service = new WecomGroupNotificationService(fetchImpl, secrets);
+
+ expect(service.setEnabled(false).enabled).toBe(false);
+ await expect(service.publishMarkdown('automation result')).rejects.toThrow(
+ 'WECOM_GROUP_NOTIFICATIONS_DISABLED',
+ );
+ expect(fetchImpl).not.toHaveBeenCalled();
+
+ expect(service.setEnabled(true).enabled).toBe(true);
+ await service.publishMarkdown('automation result');
+ expect(fetchImpl).toHaveBeenCalledOnce();
+ });
+
+ it('allows an explicit test while the automation master switch is off', async () => {
+ const fetchImpl = vi.fn(async () => response({ errcode: 0, errmsg: 'ok' }));
+ const url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abcdefgh';
+ const service = new WecomGroupNotificationService(fetchImpl, createSecrets(url, 'false'));
+
+ await service.test('Localized test message');
+
+ expect(fetchImpl).toHaveBeenCalledOnce();
});
it('does not persist a webhook when the test call fails', async () => {
@@ -93,7 +144,10 @@ describe('WeCom group notification security boundary', () => {
const service = new WecomGroupNotificationService(fetchImpl, secrets);
await expect(
- service.saveAndTest('https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abcdefgh'),
+ service.saveAndTest(
+ 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abcdefgh',
+ 'Localized test message',
+ ),
).rejects.toThrow('WECOM_GROUP_SEND_FAILED:93000');
expect(secrets.write).not.toHaveBeenCalled();
});
@@ -112,6 +166,7 @@ describe('WeCom group notification security boundary', () => {
const saving = service.saveAndTest(
'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abcdefgh',
+ 'Localized test message',
() => current,
);
await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledOnce());
@@ -133,7 +188,9 @@ describe('WeCom group notification security boundary', () => {
const url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abcdefgh';
const service = new WecomGroupNotificationService(fetchImpl, createSecrets(url));
- await expect(service.test()).rejects.toThrow('WECOM_GROUP_REDIRECT_REJECTED');
+ await expect(service.test('Localized test message')).rejects.toThrow(
+ 'WECOM_GROUP_REDIRECT_REJECTED',
+ );
});
it('serializes concurrent publishes to preserve message order', async () => {
@@ -158,4 +215,14 @@ describe('WeCom group notification security boundary', () => {
expect(bodies[0]).toContain('first');
expect(bodies[1]).toContain('second');
});
+
+ it('clears both the webhook and its master switch', () => {
+ const url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abcdefgh';
+ const secrets = createSecrets(url, 'true');
+ const service = new WecomGroupNotificationService(vi.fn(), secrets);
+
+ expect(service.clear()).toEqual({ configured: false, enabled: false });
+ expect(secrets.remove).toHaveBeenCalledWith(WEBHOOK_SECRET_NAME);
+ expect(secrets.remove).toHaveBeenCalledWith(ENABLED_SETTING_NAME);
+ });
});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 791c89d2eb..7ebb867e3f 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -268,10 +268,7 @@ import { reapClaudeOrphansSync } from './claude-orphan-reaper';
import { startAgentProcessPriorityWatcher } from './agent-process-priority';
import { initAppBadgeService, clearAllSessionAttention } from './appBadgeService';
import { initNotificationService } from './notificationService';
-import {
- initWecomGroupNotificationIpc,
- wecomGroupNotificationService,
-} from './wecomGroupNotification';
+import { initWecomGroupNotificationIpc } from './wecomGroupNotification';
import { getAgentIslandService, initAgentIslandService } from './agent-island/service.js';
import {
isAppContentWindow,
@@ -2562,7 +2559,6 @@ const registerIpcHandlers = () => {
initNotificationService({
getWindow: () => getWindow() ?? null,
feishuIm,
- wecomGroupPublisher: wecomGroupNotificationService,
});
initWecomGroupNotificationIpc();
initAgentIslandService({
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 df9360a9c4..da049b2c47 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
@@ -1248,10 +1248,12 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
it('commits one terminal payload for a chunked-text output driver', async () => {
const previousOutput = fakeAdapter.output;
+ const beginReply = vi.fn(async () => undefined);
const commitFinal = vi.fn(async () => undefined);
fakeAdapter.output = {
kind: 'chunked-text',
im: mocks.feishuIm as unknown as ChannelIM,
+ beginReply,
commitFinal,
};
try {
@@ -1264,6 +1266,8 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
await flushMicrotasks();
expect(mocks.feishuIm.startStreamingText).not.toHaveBeenCalled();
+ expect(beginReply).toHaveBeenCalledOnce();
+ expect(beginReply).toHaveBeenCalledWith('ou_user');
expect(commitFinal).toHaveBeenCalledTimes(1);
expect(commitFinal).toHaveBeenCalledWith({
userId: 'ou_user',
diff --git a/apps/desktop/src/main/im/shared/messageHandler.ts b/apps/desktop/src/main/im/shared/messageHandler.ts
index a484f82efc..e563a80299 100644
--- a/apps/desktop/src/main/im/shared/messageHandler.ts
+++ b/apps/desktop/src/main/im/shared/messageHandler.ts
@@ -16,7 +16,7 @@
* 跨渠道互不影响。
*/
-import type { ChannelIM, IMMessageEvent } from '@cindy/im';
+import type { IMMessageEvent, TextChannelIM } from '@cindy/im';
import { createLogger } from '../../logger';
import {
@@ -46,7 +46,7 @@ export function createMessageHandler(
adapter: ImChannelAdapter,
slash: ImSlashHandlers,
turnRunner: ImTurnRunner,
-): (im: ChannelIM) => () => void {
+): (im: TextChannelIM) => () => void {
const { ui, channel, threadScoped } = adapter;
const log = createLogger(`im:${channel}:msg`);
@@ -54,7 +54,7 @@ export function createMessageHandler(
const userLocks = new Map<string, Promise<void>>();
async function processOne(
- im: ChannelIM,
+ im: TextChannelIM,
event: IMMessageEvent,
accountGeneration: ImAccountGeneration,
): Promise<void> {
@@ -223,7 +223,7 @@ export function createMessageHandler(
}
}
- return function attachMessageHandler(im: ChannelIM): () => void {
+ return function attachMessageHandler(im: TextChannelIM): () => void {
return im.onMessage((event) => {
// Capture synchronously, before entering the per-user queue. A boolean
// check at execution time could accept old-account work after relogin.
diff --git a/apps/desktop/src/main/im/shared/orchestrator.ts b/apps/desktop/src/main/im/shared/orchestrator.ts
index 6756a459fd..c8497ae5a9 100644
--- a/apps/desktop/src/main/im/shared/orchestrator.ts
+++ b/apps/desktop/src/main/im/shared/orchestrator.ts
@@ -38,8 +38,9 @@ export interface ImOrchestrator {
const registry = new Map<ImChannelName, ImOrchestrator>();
/**
- * 创建并接线一个渠道编排器:订阅 im.onMessage / im.onCardAction, 注册进
- * registry。每个渠道只允许调一次(重复调说明 wiring 层 bug, 直接抛)。
+ * 创建并接线一个渠道编排器:所有渠道订阅 im.onMessage;只有 rich-card
+ * 渠道订阅 onCardAction。每个渠道只允许调一次(重复调说明 wiring 层 bug,
+ * 直接抛)。
*/
export function createImOrchestrator(adapter: ImChannelAdapter): ImOrchestrator {
if (registry.has(adapter.channel)) {
@@ -47,7 +48,12 @@ export function createImOrchestrator(adapter: ImChannelAdapter): ImOrchestrator
}
// threadScoped 渠道的能力配对断言 — thread 文案组与 messageId→threadKey
// 提取能力缺一不可, 接线期 fail-fast 好过运行时静默坏掉。
- if (adapter.threadScoped && (!adapter.ui.thread || !adapter.im.threadKeyForMessage)) {
+ if (
+ adapter.threadScoped &&
+ (adapter.output.kind !== 'rich-card' ||
+ !adapter.ui.thread ||
+ !adapter.output.im.threadKeyForMessage)
+ ) {
throw new Error(
`im orchestrator channel=${adapter.channel}: threadScoped requires ui.thread + im.threadKeyForMessage`,
);
@@ -67,10 +73,12 @@ export function createImOrchestrator(adapter: ImChannelAdapter): ImOrchestrator
});
const slash = createSlashHandlers(adapter, repo, cards, turnRunner);
const attachMessageHandler = createMessageHandler(adapter, slash, turnRunner);
- const attachCardActionHandler = createCardActionHandler(adapter, cards, turnRunner);
attachMessageHandler(adapter.im);
- attachCardActionHandler(adapter.im);
+ if (adapter.output.kind === 'rich-card') {
+ const attachCardActionHandler = createCardActionHandler(adapter, cards, turnRunner);
+ attachCardActionHandler(adapter.output.im);
+ }
const orchestrator: ImOrchestrator = {
channel: adapter.channel,
diff --git a/apps/desktop/src/main/im/shared/slashCommands.ts b/apps/desktop/src/main/im/shared/slashCommands.ts
index dd53023f8c..e3b569754b 100644
--- a/apps/desktop/src/main/im/shared/slashCommands.ts
+++ b/apps/desktop/src/main/im/shared/slashCommands.ts
@@ -72,7 +72,8 @@ export function createSlashHandlers(
cards: ImCardBuilders,
turnRunner: ImTurnRunner,
): ImSlashHandlers {
- const { im, ui, channel, threadScoped } = adapter;
+ const { im, output, ui, channel, threadScoped } = adapter;
+ const richIm = output.kind === 'rich-card' ? output.im : null;
const log = createLogger(`im:${channel}:slash`);
// threadScoped 渠道的 thread 文案组 — orchestrator 接线期已断言存在
const threadUi = ui.thread;
@@ -172,6 +173,10 @@ export function createSlashHandlers(
}
case '/model': {
+ if (!richIm) {
+ await safeSendText(ctx.userId, ui.slash.unknownCommand(cmd));
+ return true;
+ }
// thread 模型: slash 命令不携带 thread 上下文(Slack 平台限制), 无法定位
// 目标 thread/session;不拦的话 resolveRouteTarget 会误建空 scope session。
if (threadScoped && threadUi) {
@@ -220,7 +225,7 @@ export function createSlashHandlers(
: undefined,
});
try {
- await im.sendInteractiveCard(ctx.userId, spec);
+ await richIm.sendInteractiveCard(ctx.userId, spec);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
log.error(`/model card send failed: ${msg}`);
@@ -275,12 +280,16 @@ export function createSlashHandlers(
}
case '/ctr': {
+ if (!richIm) {
+ await safeSendText(ctx.userId, ui.slash.unknownCommand(cmd));
+ return true;
+ }
// ── thread 模型: 整个选择流程在"接管锚点卡"的 thread 里进行 ────────
// 顶层只发一张锚点卡(未来的接管 thread root), 工作区/会话选择卡发进
// 它的 thread — 用户从选择那一刻就在 thread 里操作, 接管完成后锚点卡
// 原地变身"已接管"(带 🚪), 同一 thread 直接续聊。
- if (threadScoped && threadUi && im.threadKeyForMessage) {
- await startThreadControlFlow(im, adapter, cards, {
+ if (threadScoped && threadUi && richIm.threadKeyForMessage) {
+ await startThreadControlFlow(richIm, adapter, cards, {
botContextId: ctx.botContextId,
userId: ctx.userId,
});
@@ -314,7 +323,7 @@ export function createSlashHandlers(
currentAttachedTitle,
});
try {
- await im.sendInteractiveCard(ctx.userId, spec);
+ await richIm.sendInteractiveCard(ctx.userId, spec);
enterControl(ctx.botContextId, ctx.userId);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
@@ -327,7 +336,7 @@ export function createSlashHandlers(
// 跨工作区最近会话直达(官方 bot /session 习惯) — 提供文案组的渠道
// 才放行; 选中走 control:session-pick 接管路径。
const recentUi = ui.cards.control.recentSessions;
- if (!recentUi) {
+ if (!richIm || !recentUi) {
await safeSendText(ctx.userId, ui.slash.unknownCommand(cmd));
return true;
}
@@ -337,7 +346,7 @@ export function createSlashHandlers(
sessions: recent,
});
try {
- await im.sendInteractiveCard(ctx.userId, spec);
+ await richIm.sendInteractiveCard(ctx.userId, spec);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
log.error(`/session card send failed: ${msg}`);
@@ -349,7 +358,7 @@ export function createSlashHandlers(
// 项目切换 — projectSwitching 渠道专属(个人 Telegram);其它渠道当
// 未知命令处理, 不暴露半成品入口。
const projectUi = ui.cards.project;
- if (!adapter.projectSwitching || !projectUi) {
+ if (!richIm || !adapter.projectSwitching || !projectUi) {
await safeSendText(ctx.userId, ui.slash.unknownCommand(cmd));
return true;
}
@@ -378,7 +387,7 @@ export function createSlashHandlers(
currentName,
});
try {
- await im.sendInteractiveCard(ctx.userId, spec);
+ await richIm.sendInteractiveCard(ctx.userId, spec);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
log.error(`/project card send failed: ${msg}`);
@@ -387,6 +396,10 @@ export function createSlashHandlers(
}
case '/permission': {
+ if (!richIm) {
+ await safeSendText(ctx.userId, ui.slash.unknownCommand(cmd));
+ return true;
+ }
if (threadScoped && threadUi) {
await safeSendText(ctx.userId, threadUi.perThreadConfigUnsupported);
return true;
@@ -406,7 +419,7 @@ export function createSlashHandlers(
currentMode: row.permissionMode,
});
try {
- await im.sendInteractiveCard(ctx.userId, spec);
+ await richIm.sendInteractiveCard(ctx.userId, spec);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
log.error(`/permission card send failed: ${msg}`);
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index 4dda807b97..b35fbf8cd0 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -178,6 +178,8 @@ interface TurnState {
/** Terminal classification consumed by chunked-text commitFinal. */
terminalKind: 'done' | 'aborted' | 'error';
terminalErrorCode: string | null;
+ /** Whether a callback-bound text response has already been reserved. */
+ chunkedReplyBegun: boolean;
queueMode: 'internal' | 'external';
terminalPromise: Promise<ImTurnTerminal>;
resolveTerminal: ((terminal: ImTurnTerminal) => void) | null;
@@ -380,6 +382,7 @@ export function createTurnRunner(
deps: ImTurnRunnerDeps = {},
): ImTurnRunner {
const { im, output, ui, channel } = adapter;
+ const richIm = output.kind === 'rich-card' ? output.im : null;
/** 过程区耗时显示的低频刷新(5s)— 单个长工具调用期间状态行不冻结。 */
const ACTIVITY_TICK_MS = 5_000;
@@ -560,7 +563,6 @@ export function createTurnRunner(
// commit 挂在它上面, 鉴权失败被拒的消息若先触发它, 这批群上下文会被游标
// 永久跳过(prepareAgentTurnText 的契约: 路由失败不推进游标)。
args.onRouteResolved?.(row.id);
-
// ── thread 名片卡(threadScoped 新 thread 会话)─────────────────────────
// 在 bot 第一条回复之前发进 thread, 让用户第一眼理解"这个 thread = 一条
// 独立会话";首条消息的 oneshot 标题生成完成后, 名片原地升级为正式标题
@@ -568,6 +570,7 @@ export function createTurnRunner(
let threadHeaderCardId: string | null = null;
const threadUiPack = adapter.ui.thread;
if (
+ richIm &&
adapter.threadScoped &&
threadUiPack &&
!target.attached &&
@@ -575,7 +578,7 @@ export function createTurnRunner(
target.scopeKey
) {
try {
- const r = await im.sendInteractiveCard(
+ const r = await richIm.sendInteractiveCard(
userId,
{ ...threadUiPack.sessionHeaderCard, buttons: [] },
{ threadTs: target.scopeKey },
@@ -623,6 +626,7 @@ export function createTurnRunner(
interactionRouteLease: null,
terminalKind: 'done',
terminalErrorCode: null,
+ chunkedReplyBegun: false,
queueMode: args.queueMode,
terminalPromise,
resolveTerminal,
@@ -755,6 +759,7 @@ export function createTurnRunner(
{ kind: 'accepted'; acceptedAt: number } | { kind: 'busy' | 'rejected'; reason: string }
> {
const rowId = item.rowId;
+ await beginChunkedReply(item.turn);
// 过程区耗时基准取真实派发时刻 — TurnState 创建时可能还要在 sendQueue 里
// 等上一轮跑完, 排队等待不该计入"第 N 步 · 耗时"显示
item.turn.activity.startedAt = Date.now();
@@ -882,6 +887,23 @@ export function createTurnRunner(
if (i >= 0) state.queue.splice(i, 1);
if (state.detachDrainPromise) {
await completeTurnCallbackAfterAck(item.turn);
+ if (
+ item.turn.queueMode === 'internal' &&
+ output.kind === 'chunked-text' &&
+ item.turn.chunkedReplyBegun
+ ) {
+ try {
+ await output.commitFinal({
+ userId,
+ text: ui.agent.sendInternalError('session_detaching'),
+ terminal: 'error',
+ threadTs: state.scopeKey,
+ errorCode: 'session_detaching',
+ });
+ } catch {
+ /* The session is already detaching; reporting remains best-effort. */
+ }
+ }
finishDeferredDetachIfIdle(state);
return { kind: 'busy', reason: 'session_detaching' };
}
@@ -910,6 +932,24 @@ export function createTurnRunner(
}
}
+ async function beginChunkedReply(turn: TurnState): Promise<void> {
+ if (
+ turn.chunkedReplyBegun ||
+ turn.queueMode !== 'internal' ||
+ output.kind !== 'chunked-text' ||
+ !output.beginReply
+ ) {
+ return;
+ }
+ turn.chunkedReplyBegun = true;
+ try {
+ await output.beginReply(turn.userId);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ log.warn(`chunked-text beginReply failed (active-send fallback): ${msg}`);
+ }
+ }
+
async function refreshSessionAfterPendingAgentSwitch(
state: SessionState,
sessionId: string,
@@ -1248,6 +1288,30 @@ export function createTurnRunner(
`publishMigrated kind=${req.kind} requestId=...${req.requestId.slice(-8)} session=...${localSessionId.slice(-8)}`,
);
+ if (!richIm) {
+ try {
+ if (adapter.handleTextInteraction) {
+ resolve(await adapter.handleTextInteraction(userId, req));
+ } else {
+ const kind = req.kind as InteractionDecision['kind'];
+ resolve(
+ kind === 'ask_user_question'
+ ? { kind, answers: {} }
+ : { kind, behavior: 'deny', reason: 'rich_output_not_supported' },
+ );
+ }
+ } catch (err) {
+ const kind = req.kind as InteractionDecision['kind'];
+ const msg = err instanceof Error ? err.message : String(err);
+ resolve(
+ kind === 'ask_user_question'
+ ? { kind, answers: {} }
+ : { kind, behavior: 'deny', reason: `text interaction failed: ${msg}` },
+ );
+ }
+ return;
+ }
+
let spec: InteractiveCardSpec | null = null;
switch (req.kind) {
case 'permission':
@@ -1279,7 +1343,7 @@ export function createTurnRunner(
let messageId: string;
try {
- const result = await im.sendInteractiveCard(userId, spec, { threadTs: scopeKey });
+ const result = await richIm.sendInteractiveCard(userId, spec, { threadTs: scopeKey });
messageId = result.messageId;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
@@ -1357,7 +1421,7 @@ export function createTurnRunner(
// (此前是「新会话(刚建好)」占位), 顶层一眼能看出 thread 对应哪条会话。
// 保留 🚪 退出按钮(updateInteractiveCard 是全量覆盖)。
const threadUiPack = adapter.ui.thread;
- if (!title || !adapter.threadScoped || !threadUiPack || !ctx?.scopeKey) return;
+ if (!richIm || !title || !adapter.threadScoped || !threadUiPack || !ctx?.scopeKey) return;
const anchorId = bindingStore.getAttachCardMessageId({
channel,
botContextId: ctx.botContextId,
@@ -1366,7 +1430,7 @@ export function createTurnRunner(
});
if (!anchorId) return;
const card = threadUiPack.takeoverCard(title, path.basename(ctx.workingDir));
- await im.updateInteractiveCard(anchorId, {
+ await richIm.updateInteractiveCard(anchorId, {
title: card.title,
body: card.body,
buttons: [
@@ -1403,8 +1467,8 @@ export function createTurnRunner(
const prefix = typeof configuredPrefix === 'function' ? configuredPrefix() : configuredPrefix;
try {
const title = await generateAndPersistFbotTitle(sessionId, text, prefix);
- if (!title || !headerCardId || !threadUiPack) return;
- await im.updateInteractiveCard(headerCardId, {
+ if (!richIm || !title || !headerCardId || !threadUiPack) return;
+ await richIm.updateInteractiveCard(headerCardId, {
...threadUiPack.sessionHeaderTitled(title),
buttons: [],
});
@@ -1736,8 +1800,9 @@ export function createTurnRunner(
): Promise<StreamingTextHandle> {
if (t.streamingHandle) return Promise.resolve(t.streamingHandle);
if (t.streamingHandlePromise) return t.streamingHandlePromise;
+ if (!richIm) return Promise.reject(new Error('rich output is not available'));
t.streamingHandlePromise = (async () => {
- const handle = await im.startStreamingText(state.userId, undefined, {
+ const handle = await richIm.startStreamingText(state.userId, undefined, {
threadTs: state.scopeKey,
});
t.streamingHandle = handle;
@@ -1986,9 +2051,23 @@ export function createTurnRunner(
await completeTurnCallbackAfterAck(failure.turn);
if (failure.turn.queueMode === 'internal') {
try {
- await im.sendText(userId, `❌ 启动 agent 失败:${failure.reason}`, {
- threadTs: state.scopeKey,
- });
+ const message = `❌ 启动 agent 失败:${failure.reason}`;
+ if (
+ output.kind === 'chunked-text' &&
+ failure.turn.chunkedReplyBegun
+ ) {
+ await output.commitFinal({
+ userId,
+ text: message,
+ terminal: 'error',
+ threadTs: state.scopeKey,
+ errorCode: failure.reason,
+ });
+ } else {
+ await im.sendText(userId, message, {
+ threadTs: state.scopeKey,
+ });
+ }
} catch {
/* 忽略失败:派发失败提示不能再阻塞收口。 */
}
@@ -2036,6 +2115,7 @@ export function createTurnRunner(
}
function patchedCardHandle(messageId: string): StreamingTextHandle {
+ if (!richIm) throw new Error('rich output is not available');
let closed = false;
let buffer = '';
let timer: ReturnType<typeof setTimeout> | null = null;
@@ -2043,7 +2123,7 @@ export function createTurnRunner(
const flush = (): void => {
timer = null;
lastPatchAt = Date.now();
- void im.patchMarkdownCard(messageId, buffer);
+ void richIm.patchMarkdownCard(messageId, buffer);
};
const schedule = (): void => {
if (closed || timer) return;
@@ -2073,7 +2153,7 @@ export function createTurnRunner(
closed = true;
cancel();
buffer = finalText;
- await im.patchMarkdownCard(messageId, finalText);
+ await richIm.patchMarkdownCard(messageId, finalText);
},
close(): void {
closed = true;
@@ -2473,7 +2553,7 @@ export function createTurnRunner(
let messageId: string;
try {
- const result = await im.sendInteractiveCard(userId, spec, { threadTs: scopeKey });
+ const result = await output.im.sendInteractiveCard(userId, spec, { threadTs: scopeKey });
messageId = result.messageId;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
diff --git a/apps/desktop/src/main/im/shared/types.ts b/apps/desktop/src/main/im/shared/types.ts
index 4dc6c14157..70015b3bfe 100644
--- a/apps/desktop/src/main/im/shared/types.ts
+++ b/apps/desktop/src/main/im/shared/types.ts
@@ -25,7 +25,7 @@ import type {
PermissionMode,
TurnPermissionPolicy,
} from '@cindy/maker-core';
-import type { ChannelIM, ImOutputDriver, IMMessageEvent, IMUnsupportedEntry } from '@cindy/im';
+import type { ImOutputDriver, IMMessageEvent, IMUnsupportedEntry, TextChannelIM } from '@cindy/im';
/** 渠道名 — 同时是 sessions.source 列值与 IdentityKey.channel 的值域。 */
export type ImChannelName =
@@ -100,8 +100,8 @@ export interface ImSessionNamespace {
*/
export interface ImChannelAdapter {
channel: ImChannelName;
- /** 收发能力(@cindy/im ChannelIM 契约)。 */
- im: ChannelIM;
+ /** 所有渠道共有的文本收发能力;富卡片能力由 output.kind 显式收窄。 */
+ im: TextChannelIM;
/** Terminal output strategy; existing channels use rich-card. */
output: ImOutputDriver;
config: ImOrchestratorConfig;
diff --git a/apps/desktop/src/main/im/wechat/adapter.ts b/apps/desktop/src/main/im/wechat/adapter.ts
index 62779a2596..5d66e1776e 100644
--- a/apps/desktop/src/main/im/wechat/adapter.ts
+++ b/apps/desktop/src/main/im/wechat/adapter.ts
@@ -1,5 +1,3 @@
-import type { RichChannelIM } from '@cindy/im';
-
import type { ImChannelAdapter, ImOrchestratorConfig } from '../shared/types';
import { resolveWechatWorkingDir } from './channelSettings';
import { ui } from './uiText';
@@ -15,10 +13,7 @@ export function buildWechatAdapter(
): ImChannelAdapter {
return {
channel: 'wechat',
- // The shared adapter type still includes rich-card methods. WechatIM makes
- // those methods fail closed, while this output discriminator guarantees
- // normal turn output only invokes commitFinal.
- im: wechatIm as RichChannelIM,
+ im: wechatIm,
output: {
kind: 'chunked-text',
im: wechatIm,
diff --git a/apps/desktop/src/main/im/wecom/adapter.ts b/apps/desktop/src/main/im/wecom/adapter.ts
index e78144cccc..6f4df7e3ad 100644
--- a/apps/desktop/src/main/im/wecom/adapter.ts
+++ b/apps/desktop/src/main/im/wecom/adapter.ts
@@ -1,6 +1,6 @@
import fs from 'node:fs';
-import type { RichChannelIM, WecomIM } from '@cindy/im';
+import type { WecomIM } from '@cindy/im';
import type { ImChannelAdapter, ImOrchestratorConfig } from '../shared/types';
import { ownerScopedImUserDataPath } from '../ownerScopedStorage';
@@ -25,10 +25,11 @@ export function buildWecomAdapter(
): ImChannelAdapter {
return {
channel: 'wecom',
- im: wecomIm as unknown as RichChannelIM,
+ im: wecomIm,
output: {
kind: 'chunked-text',
im: wecomIm,
+ beginReply: (userId) => wecomIm.beginReply(userId),
commitFinal: (output) => wecomIm.commitFinal(output),
},
config,
diff --git a/apps/desktop/src/main/im/wecom/uiText.ts b/apps/desktop/src/main/im/wecom/uiText.ts
index 0b36527282..291100fb4e 100644
--- a/apps/desktop/src/main/im/wecom/uiText.ts
+++ b/apps/desktop/src/main/im/wecom/uiText.ts
@@ -4,19 +4,17 @@ import type { ImUiTextPack } from '../shared/types';
export const ui = {
slash: {
- new: '🌱 新会话已开始,之前的上下文已清空。',
+ new: '🌱 新对话已开始,之前的上下文已清空。',
help: `🤖 可用命令:
-/new 开始新会话
-/model 切换模型
-/permission 调整权限模式
-/ctr 接管 desktop 会话
-/exctr 结束接管,回到企业微信会话
+/new 开始新对话
+/stop 中止当前任务
+/exctr 结束已有接管
/help 查看帮助
任务运行中可发送 \`!stop\` 中止当前任务并清空排队消息。`,
unknownCommand: (cmd: string) =>
- `未识别命令 \`${cmd}\`。可用命令:/new、/model、/permission、/ctr、/exctr、/help`,
+ `未识别命令 \`${cmd}\`。可用命令:/new、/stop、/exctr、/help`,
detachedBySlash: '🚪 已结束接管,后续消息回到企业微信会话。',
detachedByRevoke: '⚠️ desktop 端已收回接管,后续消息回到企业微信会话。',
notAttached: '当前没有正在接管的会话。',
diff --git a/apps/desktop/src/main/notificationService.ts b/apps/desktop/src/main/notificationService.ts
index c725e64d5f..646d4ef1fc 100644
--- a/apps/desktop/src/main/notificationService.ts
+++ b/apps/desktop/src/main/notificationService.ts
@@ -32,7 +32,6 @@ import { getMobileNotifyGeneration, sendMobileSessionNotify } from './device-lin
import { latestMessageText } from './localDb/latestMessageText';
import { drainPersistQueue } from './messagePersistBroadcaster';
import { createLogger } from './logger';
-import type { WecomGroupNotificationPublisher } from './wecomGroupNotification';
const log = createLogger('notificationService');
let desktopNotificationsEnabled = true;
@@ -76,7 +75,7 @@ interface ShowSessionEventPayload {
* mobile 通道没有桌面侧开关:是否收到由手机端自行注册/注销推送 token 决定,
* 发送侧的防打扰(远程正在看该会话 / 短窗去重)在 device-link 模块内收口。
*/
- channels?: { desktop?: boolean; feishu?: boolean; wecomGroup?: boolean; mobile?: boolean };
+ channels?: { desktop?: boolean; feishu?: boolean; mobile?: boolean };
}
/**
@@ -159,11 +158,10 @@ export interface NotificationServiceDeps {
* (main/im 模块单例),保证 owner openId 与卡片回执等行为一致。
*/
feishuIm: FeishuIM;
- wecomGroupPublisher?: WecomGroupNotificationPublisher;
}
export function initNotificationService(deps: NotificationServiceDeps): void {
- const { getWindow, feishuIm, wecomGroupPublisher } = deps;
+ const { getWindow, feishuIm } = deps;
ipcMain.handle('notification:set-desktop-enabled', (_event, enabled: unknown) => {
if (typeof enabled !== 'boolean') {
@@ -188,7 +186,6 @@ export function initNotificationService(deps: NotificationServiceDeps): void {
// channels 缺省/未传 → 默认仅桌面 (防御漏传,见 ShowSessionEventPayload 注释)。
const wantDesktop = channels?.desktop ?? true;
const wantFeishu = channels?.feishu === true;
- const wantWecomGroup = channels?.wecomGroup === true;
if (wantDesktop) {
showDesktopSessionEvent(getWindow, { sessionId, title: safeTitle, kind });
@@ -232,15 +229,6 @@ export function initNotificationService(deps: NotificationServiceDeps): void {
if (wantFeishu) {
await sendFeishuMessage(feishuIm, safeTitle, kind);
}
- if (wantWecomGroup && wecomGroupPublisher) {
- try {
- await wecomGroupPublisher.publishMarkdown(buildExternalNotificationText(safeTitle, kind));
- } catch (err) {
- log.warn('[notification] WeCom group notification failed (non-fatal)', {
- error: err instanceof Error ? err.message : String(err),
- });
- }
- }
},
);
}
diff --git a/apps/desktop/src/main/wecomGroupNotification.ts b/apps/desktop/src/main/wecomGroupNotification.ts
index dec40d8a21..418ec8d729 100644
--- a/apps/desktop/src/main/wecomGroupNotification.ts
+++ b/apps/desktop/src/main/wecomGroupNotification.ts
@@ -12,14 +12,17 @@ import { assertTrustedAppRendererEvent } from './security/trustedAppRenderer';
const log = createLogger('wecom-group-notification');
const WEBHOOK_SECRET_NAME = 'wecom-group-webhook-url';
+const ENABLED_SETTING_NAME = 'wecom-group-notification-enabled';
const WEBHOOK_HOST = 'qyapi.weixin.qq.com';
const WEBHOOK_PATH = '/cgi-bin/webhook/send';
const REQUEST_TIMEOUT_MS = 10_000;
const MAX_RESPONSE_BYTES = 16 * 1024;
const MAX_MARKDOWN_BYTES = 4_000;
+const TEST_MESSAGE_INVALID = 'WECOM_GROUP_TEST_MESSAGE_INVALID';
export interface WecomGroupNotificationState {
configured: boolean;
+ enabled: boolean;
maskedKey?: string;
}
@@ -87,6 +90,15 @@ function splitUtf8(text: string, maxBytes = MAX_MARKDOWN_BYTES): string[] {
return chunks;
}
+function parseTestMessage(raw: unknown): string {
+ if (typeof raw !== 'string') throw new TypeError('testMessage must be a string');
+ const message = raw.trim();
+ if (!message || Buffer.byteLength(message, 'utf8') > MAX_MARKDOWN_BYTES) {
+ throw new Error(TEST_MESSAGE_INVALID);
+ }
+ return message;
+}
+
async function readResponseText(response: Response): Promise<string> {
const reader = response.body?.getReader();
if (!reader) return '';
@@ -120,44 +132,73 @@ export class WecomGroupNotificationService implements WecomGroupNotificationPubl
getState(): WecomGroupNotificationState {
const stored = this.secrets.read(WEBHOOK_SECRET_NAME);
- if (!stored) return { configured: false };
+ if (!stored) return { configured: false, enabled: false };
try {
- return { configured: true, maskedKey: maskWebhookKey(parseWebhookUrl(stored)) };
+ return {
+ configured: true,
+ // Existing configurations predate the persisted master switch and
+ // remain enabled until the user explicitly turns them off.
+ enabled: this.secrets.read(ENABLED_SETTING_NAME) !== 'false',
+ maskedKey: maskWebhookKey(parseWebhookUrl(stored)),
+ };
} catch {
log.warn('stored webhook URL is invalid; treating it as unconfigured');
- return { configured: false };
+ return { configured: false, enabled: false };
+ }
+ }
+
+ setEnabled(enabled: boolean): WecomGroupNotificationState {
+ const state = this.getState();
+ if (!state.configured) throw new Error('WECOM_GROUP_WEBHOOK_NOT_CONFIGURED');
+ if (!this.secrets.write(ENABLED_SETTING_NAME, String(enabled))) {
+ throw new Error('WECOM_GROUP_ENABLED_SAVE_FAILED');
}
+ return { ...state, enabled };
}
async saveAndTest(
rawUrl: string,
+ testMessage: string,
isAccountCurrent: () => boolean = () => true,
): Promise<WecomGroupNotificationState> {
const url = parseWebhookUrl(rawUrl);
+ const message = parseTestMessage(testMessage);
await this.enqueue(() => {
if (!isAccountCurrent()) throw new ImAccountScopeClosedError();
- return this.send(url, 'Cindy 企业微信群通知测试成功');
+ return this.send(url, message);
});
if (!isAccountCurrent()) {
throw new ImAccountScopeClosedError();
}
- if (!this.secrets.write(WEBHOOK_SECRET_NAME, url.toString())) {
+ const previousUrl = this.secrets.read(WEBHOOK_SECRET_NAME);
+ const previousEnabled = this.secrets.read(ENABLED_SETTING_NAME);
+ const saved =
+ this.secrets.write(WEBHOOK_SECRET_NAME, url.toString()) &&
+ this.secrets.write(ENABLED_SETTING_NAME, 'true');
+ if (!saved) {
+ this.restoreValue(WEBHOOK_SECRET_NAME, previousUrl);
+ this.restoreValue(ENABLED_SETTING_NAME, previousEnabled);
throw new Error('WECOM_GROUP_WEBHOOK_SAVE_FAILED');
}
- return { configured: true, maskedKey: maskWebhookKey(url) };
+ return { configured: true, enabled: true, maskedKey: maskWebhookKey(url) };
}
- async test(): Promise<void> {
+ async test(testMessage: string): Promise<void> {
const url = this.requireStoredUrl();
- await this.enqueue(() => this.send(url, 'Cindy 企业微信群通知测试成功'));
+ const message = parseTestMessage(testMessage);
+ await this.enqueue(() => this.send(url, message));
}
clear(): WecomGroupNotificationState {
this.secrets.remove(WEBHOOK_SECRET_NAME);
- return { configured: false };
+ this.secrets.remove(ENABLED_SETTING_NAME);
+ return { configured: false, enabled: false };
}
async publishMarkdown(markdown: string): Promise<void> {
+ if (!this.getState().enabled) {
+ throw new Error('WECOM_GROUP_NOTIFICATIONS_DISABLED');
+ }
return this.enqueue(async () => {
const url = this.requireStoredUrl();
const chunks = splitUtf8(markdown.trim() || 'Cindy 通知');
@@ -183,6 +224,11 @@ export class WecomGroupNotificationService implements WecomGroupNotificationPubl
return parseWebhookUrl(stored);
}
+ private restoreValue(name: string, previous: string | null): void {
+ if (previous === null) this.secrets.remove(name);
+ else this.secrets.write(name, previous);
+ }
+
private async send(url: URL, markdown: string): Promise<void> {
const response = await this.fetchImpl(url.toString(), {
method: 'POST',
@@ -216,21 +262,29 @@ export function initWecomGroupNotificationIpc(): void {
assertTrustedAppRendererEvent(event);
return wecomGroupNotificationService.getState();
});
- ipcMain.handle('wecomGroupNotification:save-and-test', async (event, webhookUrl: unknown) => {
+ ipcMain.handle(
+ 'wecomGroupNotification:save-and-test',
+ async (event, webhookUrl: unknown, testMessage: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (typeof webhookUrl !== 'string') throw new TypeError('webhookUrl must be a string');
+ const accountGeneration = captureImAccountGeneration();
+ if (accountGeneration === null) throw new ImAccountScopeClosedError();
+ return runInImAccountGeneration(accountGeneration, () =>
+ wecomGroupNotificationService.saveAndTest(webhookUrl, parseTestMessage(testMessage), () =>
+ isImAccountGenerationCurrent(accountGeneration),
+ ),
+ );
+ },
+ );
+ ipcMain.handle('wecomGroupNotification:test', async (event, testMessage: unknown) => {
assertTrustedAppRendererEvent(event);
- if (typeof webhookUrl !== 'string') throw new TypeError('webhookUrl must be a string');
- const accountGeneration = captureImAccountGeneration();
- if (accountGeneration === null) throw new ImAccountScopeClosedError();
- return runInImAccountGeneration(accountGeneration, () =>
- wecomGroupNotificationService.saveAndTest(webhookUrl, () =>
- isImAccountGenerationCurrent(accountGeneration),
- ),
- );
+ await wecomGroupNotificationService.test(parseTestMessage(testMessage));
+ return { ok: true as const };
});
- ipcMain.handle('wecomGroupNotification:test', async (event) => {
+ ipcMain.handle('wecomGroupNotification:set-enabled', (event, enabled: unknown) => {
assertTrustedAppRendererEvent(event);
- await wecomGroupNotificationService.test();
- return { ok: true as const };
+ if (typeof enabled !== 'boolean') throw new TypeError('enabled must be a boolean');
+ return wecomGroupNotificationService.setEnabled(enabled);
});
ipcMain.handle('wecomGroupNotification:clear', (event) => {
assertTrustedAppRendererEvent(event);
@@ -240,5 +294,6 @@ export function initWecomGroupNotificationIpc(): void {
export const __testing = {
parseWebhookUrl,
+ parseTestMessage,
splitUtf8,
};
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 75b4c947e7..0b13ee8ca0 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -2616,18 +2616,26 @@ contextBridge.exposeInMainWorld('electronAPI', {
sessionId: string;
title: string;
kind: 'done' | 'error' | 'needs-reply';
- channels?: { desktop?: boolean; feishu?: boolean; wecomGroup?: boolean; mobile?: boolean };
+ channels?: { desktop?: boolean; feishu?: boolean; mobile?: boolean };
}): Promise<void> =>
ipcRenderer.invoke('notification:show-session-event', payload),
notificationSetDesktopEnabled: (enabled: boolean): Promise<{ ok: true }> =>
ipcRenderer.invoke('notification:set-desktop-enabled', enabled),
wecomGroupNotification: {
- getState: (): Promise<{ configured: boolean; maskedKey?: string }> =>
+ getState: (): Promise<{ configured: boolean; enabled: boolean; maskedKey?: string }> =>
ipcRenderer.invoke('wecomGroupNotification:get-state'),
- saveAndTest: (webhookUrl: string): Promise<{ configured: boolean; maskedKey?: string }> =>
- ipcRenderer.invoke('wecomGroupNotification:save-and-test', webhookUrl),
- test: (): Promise<{ ok: true }> => ipcRenderer.invoke('wecomGroupNotification:test'),
- clear: (): Promise<{ configured: boolean }> =>
+ saveAndTest: (
+ webhookUrl: string,
+ testMessage: string,
+ ): Promise<{ configured: boolean; enabled: boolean; maskedKey?: string }> =>
+ ipcRenderer.invoke('wecomGroupNotification:save-and-test', webhookUrl, testMessage),
+ test: (testMessage: string): Promise<{ ok: true }> =>
+ ipcRenderer.invoke('wecomGroupNotification:test', testMessage),
+ setEnabled: (
+ enabled: boolean,
+ ): Promise<{ configured: boolean; enabled: boolean; maskedKey?: string }> =>
+ ipcRenderer.invoke('wecomGroupNotification:set-enabled', enabled),
+ clear: (): Promise<{ configured: boolean; enabled: boolean }> =>
ipcRenderer.invoke('wecomGroupNotification:clear'),
},
notificationMarkSessionAttention: (sessionId: string): Promise<void> =>
diff --git a/apps/desktop/src/renderer/components/settings/NotificationSection.tsx b/apps/desktop/src/renderer/components/settings/NotificationSection.tsx
index d66e34b25c..245a400378 100644
--- a/apps/desktop/src/renderer/components/settings/NotificationSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/NotificationSection.tsx
@@ -1,9 +1,10 @@
/**
* NotificationSection — Settings 页"系统通知"区块。
*
- * 两个独立开关:
+ * 两个个人通知开关:
* 1. 桌面通知 — CC Agent session 完成 / 待回复时弹系统 toast(默认开)。
* 2. 飞书通知 — 同源触发,失焦时给 bot owner 私聊一条文本(默认关)。
+ * 企业微信群是共享通道,总开关控制通道可用性;每个自动操作仍需显式选择。
*
* 飞书开关的可用前提是 bot 已绑定 ownerOpenId(用户至少私聊过 bot 一次);
* 未绑定时开关禁用,并在 hint 里提示去"飞书机器人" tab 完成配置/绑定。
@@ -132,8 +133,12 @@ export function NotificationSection() {
</div>
<Switch
checked={wecomGroup.enabled && wecomGroup.configured}
- onCheckedChange={wecomGroup.setEnabled}
- disabled={!wecomGroup.configured || wecomGroup.loading}
+ onCheckedChange={(next) => {
+ void wecomGroup
+ .setEnabled(next)
+ .catch(() => toast.error(t('settings.notifications.wecomGroupToggleFailed')));
+ }}
+ disabled={!wecomGroup.configured || wecomGroup.busy}
aria-label={t('settings.notifications.wecomGroupAria')}
/>
</div>
@@ -145,7 +150,7 @@ export function NotificationSection() {
disabled={wecomGroup.busy}
onClick={() => {
void wecomGroup
- .test()
+ .test(t('settings.notifications.wecomGroupTestMessage'))
.then(() => toast.success(t('settings.notifications.wecomGroupTestSuccess')))
.catch(() => toast.error(t('settings.notifications.wecomGroupTestFailed')));
}}
@@ -203,7 +208,10 @@ export function NotificationSection() {
disabled={wecomGroup.busy || !webhookUrl.trim()}
onClick={() => {
void wecomGroup
- .saveAndTest(webhookUrl)
+ .saveAndTest(
+ webhookUrl,
+ t('settings.notifications.wecomGroupTestMessage'),
+ )
.then(() => {
setWebhookUrl('');
toast.success(t('settings.notifications.wecomGroupSaveSuccess'));
diff --git a/apps/desktop/src/renderer/components/settings/WecomBotSection.tsx b/apps/desktop/src/renderer/components/settings/WecomBotSection.tsx
index 73b69d7e21..c443e62d00 100644
--- a/apps/desktop/src/renderer/components/settings/WecomBotSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/WecomBotSection.tsx
@@ -221,8 +221,10 @@ export function WecomBotSection({
!canReconnect && 'cursor-not-allowed opacity-40',
)}
>
- {isSaving ? <Loader2 size={14} className="animate-spin" /> : null}
- {isSaving
+ {isSaving || status.kind === 'connecting' ? (
+ <Loader2 size={14} className="animate-spin" />
+ ) : null}
+ {isSaving || status.kind === 'connecting'
? t('settings.wecomBot.connectingAction')
: t('settings.wecomBot.reconnect')}
</button>
@@ -239,8 +241,10 @@ export function WecomBotSection({
!canConnect && 'cursor-not-allowed opacity-40',
)}
>
- {isSaving ? <Loader2 size={14} className="animate-spin" /> : null}
- {isSaving
+ {isSaving || status.kind === 'connecting' ? (
+ <Loader2 size={14} className="animate-spin" />
+ ) : null}
+ {isSaving || status.kind === 'connecting'
? t('settings.wecomBot.connectingAction')
: t('settings.wecomBot.connect')}
</button>
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index feb9e93d59..98bc6a0e53 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -65,7 +65,6 @@ import { useAttachedSessionIds } from '@/hooks/useAttachedSessionIds';
import { useActiveMainView } from '@/hooks/useActiveMainView';
import { getNotificationsEnabled } from '@/hooks/useNotificationSettings';
import { getFeishuNotificationsEnabled } from '@/hooks/useFeishuNotificationSettings';
-import { getWecomGroupNotificationsEnabled } from '@/hooks/useWecomGroupNotificationSettings';
import { getAgentIslandEnabled, isAgentIslandSupported } from '@/hooks/useAgentIslandSettings';
import type { Session } from '@/lib/ccAgent.types';
import {
@@ -801,7 +800,6 @@ function ExpandedView({
const islandActive = isAgentIslandSupported() && getAgentIslandEnabled();
const desktopEnabled = getNotificationsEnabled() && !islandActive;
const feishuEnabled = getFeishuNotificationsEnabled();
- const wecomGroupEnabled = getWecomGroupNotificationsEnabled();
// 失焦才推 —— 见上注释。
if (typeof document !== 'undefined' && document.hasFocus()) return;
const session = sessionsRef.current.find((s) => s.id === sessionId);
@@ -824,7 +822,6 @@ function ExpandedView({
channels: {
desktop: desktopEnabled,
feishu: feishuEnabled,
- wecomGroup: wecomGroupEnabled,
mobile: true,
},
});
diff --git a/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx b/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx
index 3cfa4d647f..df7f1ad4bb 100644
--- a/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx
+++ b/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx
@@ -381,7 +381,8 @@ export function ScheduleFormDialog({
}, [selectedTemplate, paramValues, promptDirty, setField]);
const feishuBotReady = useFeishuBot().status === 'connected';
- const wecomGroupReady = useWecomGroupNotificationSettings().configured;
+ const wecomGroupSettings = useWecomGroupNotificationSettings();
+ const wecomGroupReady = wecomGroupSettings.configured && wecomGroupSettings.enabled;
const navigate = useNavigate();
const openReferencedSession = useCallback(
async (sessionId: string) => {
diff --git a/apps/desktop/src/renderer/hooks/useWecomBot.ts b/apps/desktop/src/renderer/hooks/useWecomBot.ts
index 0e0a1d067a..5eb720082b 100644
--- a/apps/desktop/src/renderer/hooks/useWecomBot.ts
+++ b/apps/desktop/src/renderer/hooks/useWecomBot.ts
@@ -62,6 +62,7 @@ export function useWecomBot() {
setStatus(next.status);
setBotId(next.botId);
setOwnerUserId(next.ownerUserId);
+ if (next.status.kind === 'connected') setSecret('');
}),
[],
);
@@ -90,7 +91,7 @@ export function useWecomBot() {
setStatus(next.status);
setBotId(next.botId);
setOwnerUserId(next.ownerUserId);
- setSecret('');
+ if (next.status.kind === 'connected') setSecret('');
if (result.saveErrorStatus?.kind === 'error' || result.status.kind === 'error') {
toast.error(t('settings.wecomBot.connectFailed'));
return false;
@@ -176,8 +177,20 @@ export function useWecomBot() {
validationError,
isSaving,
isDisconnecting,
- canConnect: Boolean(botId.trim() && secret.trim() && !isSaving && !isDisconnecting),
- canReconnect: Boolean(botId.trim() && !secret.trim() && !isSaving && !isDisconnecting),
+ canConnect: Boolean(
+ botId.trim() &&
+ secret.trim() &&
+ status.kind !== 'connecting' &&
+ !isSaving &&
+ !isDisconnecting,
+ ),
+ canReconnect: Boolean(
+ botId.trim() &&
+ !secret.trim() &&
+ status.kind !== 'connecting' &&
+ !isSaving &&
+ !isDisconnecting,
+ ),
connect,
reconnect,
disconnect,
diff --git a/apps/desktop/src/renderer/hooks/useWecomGroupNotificationSettings.ts b/apps/desktop/src/renderer/hooks/useWecomGroupNotificationSettings.ts
index bc1fe68005..47e0e37e7a 100644
--- a/apps/desktop/src/renderer/hooks/useWecomGroupNotificationSettings.ts
+++ b/apps/desktop/src/renderer/hooks/useWecomGroupNotificationSettings.ts
@@ -1,81 +1,70 @@
import { useCallback, useEffect, useState } from 'react';
-const STORAGE_KEY = 'notifications.wecomGroupEnabled';
-const subscribers = new Set<() => void>();
-
-export function getWecomGroupNotificationsEnabled(): boolean {
- try {
- return localStorage.getItem(STORAGE_KEY) === 'true';
- } catch {
- return false;
- }
-}
-
-export function setWecomGroupNotificationsEnabled(next: boolean): void {
- try {
- localStorage.setItem(STORAGE_KEY, String(next));
- } catch {
- // Keep the in-memory UI usable when localStorage is unavailable.
- }
- for (const subscriber of subscribers) subscriber();
-}
+const LEGACY_SESSION_NOTIFICATION_KEY = 'notifications.wecomGroupEnabled';
export function useWecomGroupNotificationSettings() {
- const [enabled, setEnabledState] = useState(getWecomGroupNotificationsEnabled);
+ const [enabled, setEnabledState] = useState(false);
const [configured, setConfigured] = useState(false);
const [maskedKey, setMaskedKey] = useState<string>();
- const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState(false);
useEffect(() => {
let cancelled = false;
+ try {
+ localStorage.removeItem(LEGACY_SESSION_NOTIFICATION_KEY);
+ } catch {
+ // Legacy preference cleanup is best-effort.
+ }
void window.electronAPI.wecomGroupNotification
.getState()
.then((state) => {
if (cancelled) return;
setConfigured(state.configured);
+ setEnabledState(state.enabled);
setMaskedKey(state.maskedKey);
- if (!state.configured) setWecomGroupNotificationsEnabled(false);
})
.catch(() => {
if (!cancelled) {
setConfigured(false);
- setWecomGroupNotificationsEnabled(false);
+ setEnabledState(false);
}
- })
- .finally(() => {
- if (!cancelled) setLoading(false);
});
- const onChange = () => setEnabledState(getWecomGroupNotificationsEnabled());
- subscribers.add(onChange);
- window.addEventListener('storage', onChange);
return () => {
cancelled = true;
- subscribers.delete(onChange);
- window.removeEventListener('storage', onChange);
};
}, []);
- const setEnabled = useCallback((next: boolean) => {
- setWecomGroupNotificationsEnabled(next);
+ const setEnabled = useCallback(async (next: boolean) => {
+ setBusy(true);
+ try {
+ const state = await window.electronAPI.wecomGroupNotification.setEnabled(next);
+ setConfigured(state.configured);
+ setEnabledState(state.enabled);
+ setMaskedKey(state.maskedKey);
+ } finally {
+ setBusy(false);
+ }
}, []);
- const saveAndTest = useCallback(async (webhookUrl: string) => {
+ const saveAndTest = useCallback(async (webhookUrl: string, testMessage: string) => {
setBusy(true);
try {
- const state = await window.electronAPI.wecomGroupNotification.saveAndTest(webhookUrl);
+ const state = await window.electronAPI.wecomGroupNotification.saveAndTest(
+ webhookUrl,
+ testMessage,
+ );
setConfigured(state.configured);
+ setEnabledState(state.enabled);
setMaskedKey(state.maskedKey);
- setWecomGroupNotificationsEnabled(true);
} finally {
setBusy(false);
}
}, []);
- const test = useCallback(async () => {
+ const test = useCallback(async (testMessage: string) => {
setBusy(true);
try {
- await window.electronAPI.wecomGroupNotification.test();
+ await window.electronAPI.wecomGroupNotification.test(testMessage);
} finally {
setBusy(false);
}
@@ -86,8 +75,8 @@ export function useWecomGroupNotificationSettings() {
try {
await window.electronAPI.wecomGroupNotification.clear();
setConfigured(false);
+ setEnabledState(false);
setMaskedKey(undefined);
- setWecomGroupNotificationsEnabled(false);
} finally {
setBusy(false);
}
@@ -98,7 +87,6 @@ export function useWecomGroupNotificationSettings() {
setEnabled,
configured,
maskedKey,
- loading,
busy,
saveAndTest,
test,
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index dbb62ff057..2ae57f565f 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -468,17 +468,19 @@
"feishuHint": "Sends a private message via the linked Feishu or Lark bot; only when the window is unfocused.",
"feishuDisabledHint": "First set up the bot in \"Feishu / Lark Bot\" and DM it once to complete binding.",
"feishuAria": "Toggle session-done FeiShu notifications",
- "wecomGroupLabel": "Send notifications to a WeCom group",
- "wecomGroupHint": "Paste a WeCom group bot Webhook URL. The URL is encrypted on this device and is never shown again.",
- "wecomGroupConfiguredHint": "Configured (key {{maskedKey}}). Notifications are sent only while the window is unfocused.",
- "wecomGroupAria": "Toggle WeCom group notifications",
+ "wecomGroupLabel": "WeCom group notifications",
+ "wecomGroupHint": "Used for automation completion notifications. Paste a WeCom group bot Webhook URL; it is encrypted on this device.",
+ "wecomGroupConfiguredHint": "Configured (key {{maskedKey}}). Turn on the master switch, then enable it for each automation as needed.",
+ "wecomGroupAria": "Toggle the WeCom group notification master switch",
"wecomGroupPlaceholder": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=…",
"wecomGroupSaveAndTest": "Save and test",
"wecomGroupSaveSuccess": "Webhook saved and test message sent",
"wecomGroupSaveFailed": "Could not save or test the Webhook",
"wecomGroupTest": "Send test",
+ "wecomGroupTestMessage": "Cindy WeCom group notification test succeeded",
"wecomGroupTestSuccess": "Test message sent",
"wecomGroupTestFailed": "Test message failed",
+ "wecomGroupToggleFailed": "Could not update WeCom group notifications",
"wecomGroupClear": "Remove",
"wecomGroupCleared": "Webhook removed",
"wecomGroupClearFailed": "Could not remove the Webhook"
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index cd14a59bc8..cbb12f7c2d 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -468,17 +468,19 @@
"feishuHint": "連携済みの Feishu または Lark ボットからプライベートメッセージを送信します。ウィンドウが非アクティブの場合のみ送信。",
"feishuDisabledHint": "先に「Feishu / Lark ボット」で設定し、ボットに 1 度メッセージを送ってバインドを完了してください。",
"feishuAria": "セッション完了時の Feishu 通知を切り替え",
- "wecomGroupLabel": "WeCom グループに通知を送信",
- "wecomGroupHint": "WeCom グループボットの Webhook URL を貼り付けます。URL はこのデバイスに暗号化保存され、再表示されません。",
- "wecomGroupConfiguredHint": "設定済み(キー {{maskedKey}})。ウィンドウが非アクティブの場合のみ送信します。",
- "wecomGroupAria": "WeCom グループ通知を切り替え",
+ "wecomGroupLabel": "WeCom グループ通知",
+ "wecomGroupHint": "自動操作の完了通知に使用します。WeCom グループボットの Webhook URL を貼り付けると、このデバイスに暗号化保存されます。",
+ "wecomGroupConfiguredHint": "設定済み(キー {{maskedKey}})。全体スイッチをオンにした後、自動操作ごとに必要に応じて送信できます。",
+ "wecomGroupAria": "WeCom グループ通知の全体スイッチを切り替え",
"wecomGroupPlaceholder": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=…",
"wecomGroupSaveAndTest": "保存してテスト",
"wecomGroupSaveSuccess": "Webhook を保存し、テストメッセージを送信しました",
"wecomGroupSaveFailed": "Webhook の保存またはテストに失敗しました",
"wecomGroupTest": "テスト送信",
+ "wecomGroupTestMessage": "Cindy の WeCom グループ通知テストに成功しました",
"wecomGroupTestSuccess": "テストメッセージを送信しました",
"wecomGroupTestFailed": "テストメッセージの送信に失敗しました",
+ "wecomGroupToggleFailed": "WeCom グループ通知の設定を更新できませんでした",
"wecomGroupClear": "削除",
"wecomGroupCleared": "Webhook を削除しました",
"wecomGroupClearFailed": "Webhook を削除できませんでした"
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 597dcb36d7..f385f29870 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -468,17 +468,19 @@
"feishuHint": "연동된 Feishu 또는 Lark 봇을 통해 개인 메시지를 보냅니다. 창이 비활성 상태일 때만 전송됩니다.",
"feishuDisabledHint": "먼저 \"Feishu / Lark 봇\"에서 봇을 설정하고 한 번 메시지를 보내 바인딩을 완료하세요.",
"feishuAria": "세션 완료 Feishu 알림 전환",
- "wecomGroupLabel": "WeCom 그룹으로 알림 보내기",
- "wecomGroupHint": "WeCom 그룹 봇 Webhook URL을 붙여넣으세요. URL은 이 기기에 암호화되어 저장되며 다시 표시되지 않습니다.",
- "wecomGroupConfiguredHint": "설정됨(키 {{maskedKey}}). 창이 비활성 상태일 때만 알림을 보냅니다.",
- "wecomGroupAria": "WeCom 그룹 알림 전환",
+ "wecomGroupLabel": "WeCom 그룹 알림",
+ "wecomGroupHint": "자동 작업 완료 알림에 사용됩니다. WeCom 그룹 봇 Webhook URL을 붙여넣으면 이 기기에 암호화되어 저장됩니다.",
+ "wecomGroupConfiguredHint": "설정됨(키 {{maskedKey}}). 전체 스위치를 켠 후 각 자동 작업에서 필요할 때 전송할 수 있습니다.",
+ "wecomGroupAria": "WeCom 그룹 알림 전체 스위치 전환",
"wecomGroupPlaceholder": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=…",
"wecomGroupSaveAndTest": "저장 및 테스트",
"wecomGroupSaveSuccess": "Webhook을 저장하고 테스트 메시지를 보냈습니다",
"wecomGroupSaveFailed": "Webhook 저장 또는 테스트에 실패했습니다",
"wecomGroupTest": "테스트 전송",
+ "wecomGroupTestMessage": "Cindy WeCom 그룹 알림 테스트에 성공했습니다",
"wecomGroupTestSuccess": "테스트 메시지를 보냈습니다",
"wecomGroupTestFailed": "테스트 메시지 전송에 실패했습니다",
+ "wecomGroupToggleFailed": "WeCom 그룹 알림 설정을 업데이트하지 못했습니다",
"wecomGroupClear": "삭제",
"wecomGroupCleared": "Webhook을 삭제했습니다",
"wecomGroupClearFailed": "Webhook을 삭제하지 못했습니다"
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 1e2f57a4a8..0da162770a 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -468,17 +468,19 @@
"feishuHint": "通过已绑定的飞书或 Lark 机器人,向你私聊发送一条消息;仅在窗口失焦时发送。",
"feishuDisabledHint": "需要先在「飞书 / Lark 机器人」中配置 bot 并向它发送一条消息以完成绑定。",
"feishuAria": "切换任务完成的飞书通知",
- "wecomGroupLabel": "发送通知到企业微信群",
- "wecomGroupHint": "粘贴企微群机器人的 Webhook URL。URL 会加密保存在本机,保存后不再显示。",
- "wecomGroupConfiguredHint": "已配置(密钥 {{maskedKey}})。仅在窗口失焦时发送通知。",
- "wecomGroupAria": "切换企微群通知",
+ "wecomGroupLabel": "企业微信群通知",
+ "wecomGroupHint": "用于自动操作的完成通知。粘贴企微群机器人的 Webhook URL,URL 会加密保存在本机。",
+ "wecomGroupConfiguredHint": "已配置(密钥 {{maskedKey}})。开启总开关后,可在每个自动操作中按需发送。",
+ "wecomGroupAria": "切换企业微信群通知总开关",
"wecomGroupPlaceholder": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=…",
"wecomGroupSaveAndTest": "保存并测试",
"wecomGroupSaveSuccess": "Webhook 已保存,测试消息已发送",
"wecomGroupSaveFailed": "Webhook 保存或测试失败",
"wecomGroupTest": "发送测试",
+ "wecomGroupTestMessage": "Cindy 企业微信群通知测试成功",
"wecomGroupTestSuccess": "测试消息已发送",
"wecomGroupTestFailed": "测试消息发送失败",
+ "wecomGroupToggleFailed": "企业微信群通知开关更新失败",
"wecomGroupClear": "移除",
"wecomGroupCleared": "Webhook 已移除",
"wecomGroupClearFailed": "Webhook 移除失败"
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 2f3b5d510c..86c34f9ac7 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -2168,15 +2168,21 @@ interface ElectronAPI {
* mobile = 手机推送:桌面侧无独立开关(手机端注册/注销 token 决定接收),
* 发送侧防打扰在 main 的 device-link 模块收口,renderer 恒传 true。
*/
- channels?: { desktop?: boolean; feishu?: boolean; wecomGroup?: boolean; mobile?: boolean };
+ channels?: { desktop?: boolean; feishu?: boolean; mobile?: boolean };
}) => Promise<void>;
/** Sync the renderer-owned global desktop-notification preference to main. */
notificationSetDesktopEnabled?: (enabled: boolean) => Promise<{ ok: true }>;
wecomGroupNotification: {
- getState: () => Promise<{ configured: boolean; maskedKey?: string }>;
- saveAndTest: (webhookUrl: string) => Promise<{ configured: boolean; maskedKey?: string }>;
- test: () => Promise<{ ok: true }>;
- clear: () => Promise<{ configured: boolean }>;
+ getState: () => Promise<{ configured: boolean; enabled: boolean; maskedKey?: string }>;
+ saveAndTest: (
+ webhookUrl: string,
+ testMessage: string,
+ ) => Promise<{ configured: boolean; enabled: boolean; maskedKey?: string }>;
+ test: (testMessage: string) => Promise<{ ok: true }>;
+ setEnabled: (
+ enabled: boolean,
+ ) => Promise<{ configured: boolean; enabled: boolean; maskedKey?: string }>;
+ clear: () => Promise<{ configured: boolean; enabled: boolean }>;
};
/** 将对应 session 标记为需要关注,显示 Dock/taskbar app badge。 */
notificationMarkSessionAttention: (sessionId: string) => Promise<void>;
diff --git a/packages/lizi-im/src/channelIM.ts b/packages/lizi-im/src/channelIM.ts
index 5025410daf..e32268fe97 100644
--- a/packages/lizi-im/src/channelIM.ts
+++ b/packages/lizi-im/src/channelIM.ts
@@ -134,5 +134,10 @@ export type ImOutputDriver =
| {
kind: 'chunked-text';
im: TextChannelIM;
+ /**
+ * Reserve an inbound reply context before a potentially long turn.
+ * Transports with callback deadlines may emit a non-terminal placeholder.
+ */
+ beginReply?(userId: string): Promise<void>;
commitFinal(output: ImFinalOutput): Promise<void>;
};
diff --git a/packages/lizi-im/src/wecom/__tests__/index.test.ts b/packages/lizi-im/src/wecom/__tests__/index.test.ts
index 5dc23f192d..e4cf18382e 100644
--- a/packages/lizi-im/src/wecom/__tests__/index.test.ts
+++ b/packages/lizi-im/src/wecom/__tests__/index.test.ts
@@ -4,13 +4,20 @@ import type { IMHost, IMMessageEvent } from "../../types.js";
import { decodeWecomLane } from "../codec.js";
import { WecomIM } from "../index.js";
-type Handler = (...args: any[]) => void;
+type Handler = (payload?: unknown) => void;
class FakeClient {
readonly handlers = new Map<string, Handler[]>();
readonly sendMessage = vi.fn(async () => ({}));
readonly sendMediaMessage = vi.fn(async () => ({}));
- readonly replyStream = vi.fn(async () => ({}));
+ readonly replyStream = vi.fn<
+ (
+ frame: unknown,
+ streamId: string,
+ content: string,
+ finish: boolean,
+ ) => Promise<Record<string, never>>
+ >(async () => ({}));
readonly replyMedia = vi.fn(async () => ({}));
readonly uploadMedia = vi.fn(async () => ({ media_id: "media-1" }));
readonly downloadFile = vi.fn(async () => ({
@@ -153,6 +160,78 @@ describe("WecomIM routing and ownership", () => {
});
});
+ it("starts a passive stream before the turn and finalizes the same stream", async () => {
+ const { host, secrets } = createHost();
+ secrets.set("wecom-owner-user-id", "owner");
+ const client = new FakeClient();
+ const im = new WecomIM(host, {
+ clientFactory: () => client as never,
+ now: () => 1_000,
+ });
+
+ await im.init();
+ const frame = message({ id: "m-stream", sender: "owner", text: "task" });
+ client.emit("message.text", frame);
+ await flush();
+
+ await im.beginReply("owner");
+ const streamId = client.replyStream.mock.calls[0]?.[1];
+ expect(client.replyStream).toHaveBeenNthCalledWith(
+ 1,
+ frame,
+ expect.any(String),
+ " ",
+ false,
+ );
+
+ await im.commitFinal({
+ userId: "owner",
+ text: "final answer",
+ terminal: "done",
+ });
+
+ expect(client.replyStream).toHaveBeenNthCalledWith(
+ 2,
+ frame,
+ streamId,
+ "final answer",
+ true,
+ );
+ expect(client.sendMessage).not.toHaveBeenCalled();
+ });
+
+ it("falls back to active send after the passive stream safety window", async () => {
+ const { host, secrets } = createHost();
+ secrets.set("wecom-owner-user-id", "owner");
+ const client = new FakeClient();
+ let now = 1_000;
+ const im = new WecomIM(host, {
+ clientFactory: () => client as never,
+ now: () => now,
+ });
+
+ await im.init();
+ client.emit(
+ "message.text",
+ message({ id: "m-timeout", sender: "owner", text: "long task" }),
+ );
+ await flush();
+ await im.beginReply("owner");
+ now += 5 * 60_000;
+
+ await im.commitFinal({
+ userId: "owner",
+ text: "late answer",
+ terminal: "done",
+ });
+
+ expect(client.replyStream).toHaveBeenCalledTimes(1);
+ expect(client.sendMessage).toHaveBeenCalledWith("owner", {
+ msgtype: "markdown",
+ markdown: { content: "late answer" },
+ });
+ });
+
it("deduplicates repeated callback message ids", async () => {
const { host, secrets } = createHost();
secrets.set("wecom-owner-user-id", "owner");
@@ -184,6 +263,29 @@ describe("WecomIM routing and ownership", () => {
});
});
+ it("preserves the concrete authentication failure after retries are exhausted", async () => {
+ const { host } = createHost();
+ const client = new FakeClient();
+ const im = new WecomIM(host, { clientFactory: () => client as never });
+
+ await im.init();
+ client.emit(
+ "error",
+ new Error("Authentication failed: invalid secret (code: 40001)"),
+ );
+ client.emit(
+ "error",
+ Object.assign(new Error("Max auth failure attempts exceeded (3)"), {
+ code: "WS_AUTH_FAILURE_EXHAUSTED",
+ }),
+ );
+
+ expect(im.getStatus()).toEqual({
+ kind: "error",
+ reason: "企业微信鉴权失败:invalid secret (code: 40001)",
+ });
+ });
+
it("preserves arrival order when media download is slower than a following text message", async () => {
const { host, secrets } = createHost();
secrets.set("wecom-owner-user-id", "owner");
diff --git a/packages/lizi-im/src/wecom/index.ts b/packages/lizi-im/src/wecom/index.ts
index f0e79e5c02..e4ac2808f3 100644
--- a/packages/lizi-im/src/wecom/index.ts
+++ b/packages/lizi-im/src/wecom/index.ts
@@ -42,6 +42,7 @@ const BOT_SECRET_SECRET_KEY = "wecom-bot-secret";
const OWNER_USER_ID_SECRET_KEY = "wecom-owner-user-id";
const CALLBACK_TTL_MS = 4 * 60_000;
const CALLBACK_QUEUE_CAPACITY = 64;
+const STREAM_SAFE_TIMEOUT_MS = 5 * 60_000;
const DEDUPE_CAPACITY = 2_048;
const SECRET_WRITE_FAILED_REASON = "无法使用系统安全存储保存企业微信机器人凭证";
@@ -55,16 +56,25 @@ interface PendingFrame {
receivedAt: number;
}
+interface PendingResponse {
+ frame: WecomFrame | null;
+ streamId: string;
+ startedAt: number;
+ passiveStarted: boolean;
+}
+
export interface WecomIMOptions {
clientFactory?: (options: WSClientOptions) => WSClient;
now?: () => number;
}
+/** Enterprise WeChat transport with durable chunked-text output. */
export class WecomIM extends BaseIM implements TextChannelIM {
private readonly messageHandlers = new Set<MessageHandler>();
private readonly statusHandlers = new Set<StatusHandler>();
private readonly textInterceptors = new Set<TextInterceptor>();
private readonly pendingFrames = new Map<string, PendingFrame[]>();
+ private readonly pendingResponses = new Map<string, PendingResponse[]>();
private readonly inboundTails = new Map<string, Promise<void>>();
private readonly seenMessageIds = new Set<string>();
private readonly mediaDir: string;
@@ -73,6 +83,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {
private status: IMStatus = { kind: "idle" };
private botId = "";
private ownerUserId = "";
+ private lastAuthFailureReason = "";
private generation = 0;
constructor(
@@ -104,6 +115,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {
async dispose(): Promise<void> {
this.generation += 1;
this.pendingFrames.clear();
+ this.pendingResponses.clear();
this.inboundTails.clear();
this.seenMessageIds.clear();
this.client?.disconnect();
@@ -182,6 +194,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {
this.client?.disconnect();
this.client = null;
this.pendingFrames.clear();
+ this.pendingResponses.clear();
this.inboundTails.clear();
this.seenMessageIds.clear();
this.host.secrets.remove(BOT_ID_SECRET_KEY);
@@ -274,9 +287,35 @@ export class WecomIM extends BaseIM implements TextChannelIM {
}
}
+ /**
+ * Preserve the callback reply window before the Agent starts. The final
+ * response reuses this stream id; after the safe window it falls back to an
+ * active markdown message.
+ */
+ async beginReply(userId: string): Promise<void> {
+ const client = this.requireConnectedClient();
+ const response: PendingResponse = {
+ frame: this.claimOldestFrame(userId),
+ streamId: randomUUID(),
+ startedAt: this.now(),
+ passiveStarted: false,
+ };
+ this.enqueueResponse(userId, response);
+ if (!response.frame) return;
+ try {
+ await client.replyStream(response.frame, response.streamId, " ", false);
+ response.passiveStarted = true;
+ } catch (error) {
+ this.log.warn(
+ "failed to start passive stream; final reply will use active send",
+ safeError(error),
+ );
+ }
+ }
+
async commitFinal(output: ImFinalOutput): Promise<void> {
const chunks = chunkWecomMarkdown(output.text);
- await this.sendChunks(output.userId, chunks, "oldest");
+ await this.sendFinalChunks(output.userId, chunks);
for (const absPath of output.mediaAbsPaths?.slice(0, 4) ?? []) {
const result = await this.sendFile(output.userId, absPath);
if (!result.ok) {
@@ -291,6 +330,8 @@ export class WecomIM extends BaseIM implements TextChannelIM {
const generation = (this.generation += 1);
this.client?.disconnect();
this.pendingFrames.clear();
+ this.pendingResponses.clear();
+ this.lastAuthFailureReason = "";
this.setStatus({ kind: "connecting" });
const clientFactory =
@@ -320,7 +361,17 @@ export class WecomIM extends BaseIM implements TextChannelIM {
client.on("error", (error) => {
if (!this.isCurrent(client, generation)) return;
this.log.warn("connection error", safeError(error));
- this.setStatus({ kind: "error", reason: sanitizeReason(error.message) });
+ const code = errorCode(error);
+ if (/^Authentication failed:/iu.test(error.message)) {
+ this.lastAuthFailureReason = formatAuthFailureReason(error.message);
+ }
+ this.setStatus({
+ kind: "error",
+ reason:
+ code === "WS_AUTH_FAILURE_EXHAUSTED"
+ ? this.lastAuthFailureReason || "企业微信鉴权失败,请检查 Bot ID、Secret 和长连接模式"
+ : this.lastAuthFailureReason || sanitizeReason(error.message),
+ });
});
client.on("event.disconnected_event", () => {
if (!this.isCurrent(client, generation)) return;
@@ -672,6 +723,46 @@ export class WecomIM extends BaseIM implements TextChannelIM {
return { messageId: firstId };
}
+ private async sendFinalChunks(
+ userId: string,
+ chunks: string[],
+ ): Promise<{ messageId: string }> {
+ const client = this.requireConnectedClient();
+ const lane = decodeWecomLane(userId);
+ const response = this.claimOldestResponse(userId);
+ const messageId = response?.streamId ?? randomUUID();
+ let start = 0;
+
+ if (
+ response?.frame &&
+ response.passiveStarted &&
+ this.now() - response.startedAt < STREAM_SAFE_TIMEOUT_MS
+ ) {
+ try {
+ await client.replyStream(
+ response.frame,
+ response.streamId,
+ chunks[0] ?? " ",
+ true,
+ );
+ start = 1;
+ } catch (error) {
+ this.log.warn(
+ "passive stream finalization failed; using active send",
+ safeError(error),
+ );
+ }
+ }
+
+ for (let index = start; index < chunks.length; index += 1) {
+ await client.sendMessage(lane.targetId, {
+ msgtype: "markdown",
+ markdown: { content: chunks[index]! },
+ });
+ }
+ return { messageId };
+ }
+
private requireConnectedClient(): WSClient {
if (!this.client || !this.client.isConnected)
throw new Error("WECOM_NOT_CONNECTED");
@@ -710,6 +801,21 @@ export class WecomIM extends BaseIM implements TextChannelIM {
this.pendingFrames.set(lane, queue);
}
+ private enqueueResponse(lane: string, response: PendingResponse): void {
+ const queue = this.pendingResponses.get(lane) ?? [];
+ queue.push(response);
+ while (queue.length > CALLBACK_QUEUE_CAPACITY) queue.shift();
+ this.pendingResponses.set(lane, queue);
+ }
+
+ private claimOldestResponse(lane: string): PendingResponse | null {
+ const queue = this.pendingResponses.get(lane) ?? [];
+ const found = queue.shift() ?? null;
+ if (queue.length) this.pendingResponses.set(lane, queue);
+ else this.pendingResponses.delete(lane);
+ return found;
+ }
+
private claimNewestFrame(lane: string): WecomFrame | null {
const queue = this.liveFrames(lane);
const found = queue.pop()?.frame ?? null;
@@ -843,6 +949,16 @@ function sanitizeReason(reason: string): string {
.slice(0, 240);
}
+function formatAuthFailureReason(message: string): string {
+ const detail = sanitizeReason(message).replace(
+ /^Authentication failed:\s*/iu,
+ "",
+ );
+ return detail
+ ? `企业微信鉴权失败:${detail}`
+ : "企业微信鉴权失败,请检查 Bot ID、Secret 和长连接模式";
+}
+
function safeError(error: unknown): { code: string; message: string } {
return {
code: errorCode(error),