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): preserve prompts and account boundaries

davidc7d9719eb7b4
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 92b52fd205..8fac950846 100644
--- a/apps/desktop/src/main/im/wecom/__tests__/textInteractions.test.ts
+++ b/apps/desktop/src/main/im/wecom/__tests__/textInteractions.test.ts
@@ -1,7 +1,8 @@
import type { InteractionRequest } from '@cindy/maker-core';
-import { describe, expect, it } from 'vitest';
+import type { IMStatus, WecomIM } from '@cindy/im';
+import { describe, expect, it, vi } from 'vitest';
-import { formatWecomInteractionPrompt } from '../textInteractions';
+import { formatWecomInteractionPrompt, WecomTextInteractions } from '../textInteractions';
function permissionRequest(input: Record<string, unknown>): InteractionRequest {
return {
@@ -44,4 +45,37 @@ describe('formatWecomInteractionPrompt', () => {
expect(formatWecomInteractionPrompt(permissionRequest(input))).toContain('<无法序列化>');
});
+
+ it('保留模板 Markdown,并阻止参数内容闭合代码围栏', () => {
+ const prompt = formatWecomInteractionPrompt(
+ permissionRequest({ command: '```markdown\n@all' }),
+ );
+
+ expect(prompt.match(/```/g)).toHaveLength(2);
+ expect(prompt).toContain('\\u0060\\u0060\\u0060markdown');
+ });
+
+ it('通过 Markdown 通道发送审批模板', async () => {
+ const sendMarkdownText = vi.fn(async () => ({ messageId: 'message-1' }));
+ const sendText = vi.fn(async () => ({ messageId: 'message-2' }));
+ const onStatusChange = vi.fn((handler: (status: IMStatus) => void) => {
+ void handler;
+ return () => undefined;
+ });
+ const im = {
+ onTextMessageIntercept: vi.fn(() => () => undefined),
+ onStatusChange,
+ sendMarkdownText,
+ sendText,
+ } as unknown as WecomIM;
+ const interactions = new WecomTextInteractions(im);
+
+ const result = interactions.handle('owner', permissionRequest({ command: 'pnpm test' }));
+ await vi.waitFor(() => expect(sendMarkdownText).toHaveBeenCalledOnce());
+ expect(sendText).not.toHaveBeenCalled();
+ const statusHandler = onStatusChange.mock.calls[0]?.[0];
+ expect(statusHandler).toBeDefined();
+ statusHandler?.({ kind: 'idle' });
+ await result;
+ });
});
diff --git a/apps/desktop/src/main/im/wecom/textInteractions.ts b/apps/desktop/src/main/im/wecom/textInteractions.ts
index f5ca2e432f..efb79a9e89 100644
--- a/apps/desktop/src/main/im/wecom/textInteractions.ts
+++ b/apps/desktop/src/main/im/wecom/textInteractions.ts
@@ -1,5 +1,5 @@
import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core';
-import type { IMMessageEvent, WecomIM } from '@cindy/im';
+import { escapeWecomMarkdown, type IMMessageEvent, type WecomIM } from '@cindy/im';
interface PendingInteraction {
request: InteractionRequest;
@@ -39,7 +39,7 @@ export class WecomTextInteractions {
this.pending.set(userId, { request, resolve: resolvePending, timer });
try {
- await this.im.sendText(userId, formatWecomInteractionPrompt(request));
+ await this.im.sendMarkdownText(userId, formatWecomInteractionPrompt(request));
} catch (error) {
const current = this.pending.get(userId);
if (current?.request.requestId === request.requestId) {
@@ -85,9 +85,12 @@ function previewPermissionInput(input: Record<string, unknown>): string {
try {
const json = JSON.stringify(input, null, 2);
if (!json) return '<无法序列化>';
- return json.length > MAX_PERMISSION_INPUT_PREVIEW
+ const preview = json.length > MAX_PERMISSION_INPUT_PREVIEW
? `${json.slice(0, MAX_PERMISSION_INPUT_PREVIEW)}\n…(已截断)`
: json;
+ // Keep the surrounding template fence intact even when a string value
+ // contains model-controlled backticks. JSON's unicode escape stays valid.
+ return preview.replaceAll('`', '\\u0060');
} catch {
return '<无法序列化>';
}
@@ -95,7 +98,8 @@ function previewPermissionInput(input: Record<string, unknown>): string {
export function formatWecomInteractionPrompt(request: InteractionRequest): string {
if (request.kind === 'permission') {
- return `需要确认工具“${request.displayName ?? request.toolName}”。
+ const toolName = escapeWecomMarkdown(request.displayName ?? request.toolName);
+ return `需要确认工具“${toolName}”。
参数:
\`\`\`json
@@ -116,10 +120,10 @@ ${plan}
if (!question) return 'Agent 正在等待你的回答,但没有可显示的问题。请回复“继续”。';
const options = (question.options ?? [])
.slice(0, 9)
- .map((option, index) => `${index + 1}. ${option.label}`)
+ .map((option, index) => `${index + 1}. ${escapeWecomMarkdown(option.label)}`)
.join('\n');
return `Agent 需要你的回答:
-${question.question}
+${escapeWecomMarkdown(question.question)}
${options ? `\n${options}\n` : ''}
请回复选项序号,或直接输入你的回答。`;
}
diff --git a/packages/lizi-im/src/index.ts b/packages/lizi-im/src/index.ts
index 2ca4599bba..62b6300cb8 100644
--- a/packages/lizi-im/src/index.ts
+++ b/packages/lizi-im/src/index.ts
@@ -49,6 +49,7 @@ export {
decodeWecomLane,
encodeWecomGroupLane,
chunkWecomMarkdown,
+ escapeWecomMarkdown,
} from './wecom/codec.js';
export {
decodeLaneUserId as decodeTelegramLaneUserId,
diff --git a/packages/lizi-im/src/wecom/__tests__/index.test.ts b/packages/lizi-im/src/wecom/__tests__/index.test.ts
index 2f113ec5db..032b053127 100644
--- a/packages/lizi-im/src/wecom/__tests__/index.test.ts
+++ b/packages/lizi-im/src/wecom/__tests__/index.test.ts
@@ -293,6 +293,32 @@ describe("WecomIM routing and ownership", () => {
}
});
+ it("reports attachments omitted by the outbound safety cap", 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 });
+ const sendFile = vi
+ .spyOn(im, "sendFile")
+ .mockResolvedValue({ ok: true, messageId: "attachment" });
+
+ await im.init();
+ await im.commitFinal({
+ userId: "owner",
+ text: "done",
+ terminal: "done",
+ mediaAbsPaths: ["one", "two", "three", "four", "five"],
+ });
+
+ expect(sendFile).toHaveBeenCalledTimes(4);
+ expect(client.sendMessage).toHaveBeenCalledWith("owner", {
+ msgtype: "markdown",
+ markdown: {
+ content: "done\n\n⚠️ 另有 1 个附件未发送(企业微信单次最多发送 4 个)。",
+ },
+ });
+ });
+
it("deduplicates repeated callback message ids", async () => {
const { host, secrets } = createHost();
secrets.set("wecom-owner-user-id", "owner");
@@ -583,6 +609,48 @@ describe("WecomIM routing and ownership", () => {
expect(cacheMedia).not.toHaveBeenCalled();
});
+ it("does not stage inbound media after the owning account boundary closes", async () => {
+ const { host, secrets } = createHost();
+ secrets.set("wecom-owner-user-id", "owner");
+ const accountToken = { id: 1 };
+ let accountActive = true;
+ host.accountScope = {
+ capture: () => (accountActive ? accountToken : null),
+ isCurrent: (token) => accountActive && token === accountToken,
+ run: async (_token, operation) => operation(),
+ };
+ const client = new FakeClient();
+ const cacheMedia = vi.fn(async () => ({
+ absPath: "C:\\managed\\clip.mp4",
+ url: `cindy-media://blobs/${"a".repeat(64)}.mp4`,
+ mimeType: "video/mp4",
+ }));
+ host.media = {
+ cacheImage: vi.fn(),
+ cacheMedia,
+ getCachedImage: vi.fn(async () => null),
+ resolveMediaUrl: vi.fn(() => null),
+ };
+ const im = new WecomIM(host, { clientFactory: () => client as never });
+
+ await im.init();
+ accountActive = false;
+ client.emit("message.video", {
+ body: {
+ msgid: "closed-account-video",
+ aibotid: "bot-1",
+ chattype: "single",
+ from: { userid: "owner" },
+ msgtype: "video",
+ video: { url: "https://example.invalid/video" },
+ },
+ });
+ await flush();
+
+ expect(client.downloadFile).not.toHaveBeenCalled();
+ expect(cacheMedia).not.toHaveBeenCalled();
+ });
+
it("routes inbound video bytes through the host media ledger", 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 156bf82fc7..7c31297660 100644
--- a/packages/lizi-im/src/wecom/index.ts
+++ b/packages/lizi-im/src/wecom/index.ts
@@ -50,7 +50,9 @@ 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 MAX_TERMINAL_ATTACHMENTS = 4;
const SECRET_WRITE_FAILED_REASON = "无法使用系统安全存储保存企业微信机器人凭证";
+const NO_ACCOUNT_SCOPE = Symbol("no-account-scope");
type MessageHandler = (event: IMMessageEvent) => void;
type StatusHandler = (status: IMStatus) => void;
@@ -91,6 +93,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {
private ownerUserId = "";
private lastAuthFailureReason = "";
private generation = 0;
+ private accountToken: unknown = NO_ACCOUNT_SCOPE;
constructor(
host: IMHost,
@@ -361,12 +364,24 @@ export class WecomIM extends BaseIM implements TextChannelIM {
}
for (const absPath of output.mediaAbsPaths ?? []) addAttachment(absPath);
- const visibleText = stripXdtFileLinks(stripXdtImageLinks(output.text)).trim();
+ const omittedAttachmentCount = Math.max(
+ 0,
+ attachments.length - MAX_TERMINAL_ATTACHMENTS,
+ );
+ const attachmentNotice = omittedAttachmentCount
+ ? `⚠️ 另有 ${omittedAttachmentCount} 个附件未发送(企业微信单次最多发送 ${MAX_TERMINAL_ATTACHMENTS} 个)。`
+ : "";
+ const visibleText = [
+ stripXdtFileLinks(stripXdtImageLinks(output.text)).trim(),
+ attachmentNotice,
+ ]
+ .filter(Boolean)
+ .join("\n\n");
const chunks = chunkWecomMarkdown(
visibleText || (attachments.length > 0 ? "📎 附件如下" : "_(空回复)_"),
);
await this.sendFinalChunks(output.userId, chunks);
- for (const attachment of attachments.slice(0, 4)) {
+ for (const attachment of attachments.slice(0, MAX_TERMINAL_ATTACHMENTS)) {
const result = await this.sendFile(
output.userId,
attachment.absPath,
@@ -382,6 +397,9 @@ export class WecomIM extends BaseIM implements TextChannelIM {
private connect(botId: string, secret: string): void {
const generation = (this.generation += 1);
+ this.accountToken = this.host.accountScope
+ ? this.host.accountScope.capture()
+ : NO_ACCOUNT_SCOPE;
this.client?.disconnect();
this.pendingFrames.clear();
this.pendingResponses.clear();
@@ -935,7 +953,14 @@ export class WecomIM extends BaseIM implements TextChannelIM {
}
private isCurrent(client: WSClient, generation: number): boolean {
- return this.client === client && this.generation === generation;
+ if (this.client !== client || this.generation !== generation) return false;
+ const accountScope = this.host.accountScope;
+ if (!accountScope) return true;
+ return (
+ this.accountToken !== NO_ACCOUNT_SCOPE &&
+ this.accountToken !== null &&
+ accountScope.isCurrent(this.accountToken)
+ );
}
private setStatus(status: IMStatus): void {