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): harden interactions and terminal attachments

david26c643b59365
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 850248214e..ca9796c4a8 100644
--- a/apps/desktop/src/main/im/wecom/__tests__/textInteractions.test.ts
+++ b/apps/desktop/src/main/im/wecom/__tests__/textInteractions.test.ts
@@ -55,7 +55,7 @@ describe('formatWecomInteractionPrompt', () => {
expect(prompt).toContain('\\u0060\\u0060\\u0060markdown');
});
- it('通过 Markdown 通道发送审批模板', async () => {
+ 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) => {
@@ -70,13 +70,25 @@ describe('formatWecomInteractionPrompt', () => {
} 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;
+ const terminalStatuses: IMStatus[] = [
+ { kind: 'idle' },
+ { kind: 'conflict', appId: 'bot-1' },
+ { kind: 'error', reason: 'connection_failed' },
+ ];
+
+ for (const [index, status] of terminalStatuses.entries()) {
+ const result = interactions.handle('owner', permissionRequest({ command: 'pnpm test' }));
+ await vi.waitFor(() => expect(sendMarkdownText).toHaveBeenCalledTimes(index + 1));
+ statusHandler?.(status);
+ await expect(result).resolves.toEqual({
+ kind: 'permission',
+ behavior: 'deny',
+ reason: 'wecom_interaction_disconnected',
+ });
+ }
+ expect(sendText).not.toHaveBeenCalled();
});
it('待审批时让 !stop 绕过拦截器并收口当前请求', async () => {
diff --git a/apps/desktop/src/main/im/wecom/textInteractions.ts b/apps/desktop/src/main/im/wecom/textInteractions.ts
index 2441ef1c45..94f79692f8 100644
--- a/apps/desktop/src/main/im/wecom/textInteractions.ts
+++ b/apps/desktop/src/main/im/wecom/textInteractions.ts
@@ -18,7 +18,9 @@ export class WecomTextInteractions {
constructor(private readonly im: WecomIM) {
im.onTextMessageIntercept((event) => this.consume(event));
im.onStatusChange((status) => {
- if (status.kind === 'idle') this.cancelAll('wecom_interaction_disconnected');
+ if (status.kind === 'idle' || status.kind === 'conflict' || status.kind === 'error') {
+ this.cancelAll('wecom_interaction_disconnected');
+ }
});
}
diff --git a/packages/lizi-im/src/wecom/__tests__/index.test.ts b/packages/lizi-im/src/wecom/__tests__/index.test.ts
index f94e3d1a2a..8fec851c45 100644
--- a/packages/lizi-im/src/wecom/__tests__/index.test.ts
+++ b/packages/lizi-im/src/wecom/__tests__/index.test.ts
@@ -222,6 +222,64 @@ describe("WecomIM routing and ownership", () => {
expect(client.sendMessage).not.toHaveBeenCalled();
});
+ it("keeps later inbound frames available while terminal attachments use active send", async () => {
+ const { host, secrets } = createHost();
+ secrets.set("wecom-owner-user-id", "owner");
+ const client = new FakeClient();
+ const mediaDir = join(tmpdir(), `cindy-wecom-frame-${randomUUID()}`);
+ const filePath = join(mediaDir, "report.txt");
+ const im = new WecomIM(host, { clientFactory: () => client as never });
+
+ await mkdir(mediaDir, { recursive: true });
+ await writeFile(filePath, "report");
+ try {
+ await im.init();
+ const firstFrame = message({
+ id: "m-first",
+ sender: "owner",
+ text: "first",
+ });
+ const secondFrame = message({
+ id: "m-second",
+ sender: "owner",
+ text: "second",
+ });
+ client.emit("message.text", firstFrame);
+ await flush();
+ await im.beginReply("owner");
+ client.uploadMedia.mockImplementationOnce(async () => {
+ client.emit("message.text", secondFrame);
+ await flush();
+ return { media_id: "media-2" };
+ });
+
+ const fileUrl = `xdt-file:///${encodeURI(filePath.replaceAll("\\", "/"))}`;
+ await im.commitFinal({
+ userId: "owner",
+ text: `done\n[report](${fileUrl})`,
+ terminal: "done",
+ allowedFileRoots: [mediaDir],
+ });
+
+ expect(client.replyMedia).not.toHaveBeenCalled();
+ expect(client.sendMediaMessage).toHaveBeenCalledWith(
+ "owner",
+ "file",
+ "media-2",
+ );
+ await im.sendMarkdownText("owner", "second reply");
+ expect(client.replyStream).toHaveBeenLastCalledWith(
+ secondFrame,
+ expect.any(String),
+ "second reply",
+ true,
+ );
+ } finally {
+ await im.dispose();
+ await rm(mediaDir, { recursive: true, force: true });
+ }
+ });
+
it("falls back to active send after the passive stream safety window", async () => {
const { host, secrets } = createHost();
secrets.set("wecom-owner-user-id", "owner");
@@ -300,6 +358,34 @@ describe("WecomIM routing and ownership", () => {
}
});
+ it("reports managed images that cannot be resolved before removing their links", async () => {
+ const { host, secrets } = createHost();
+ secrets.set("wecom-owner-user-id", "owner");
+ const client = new FakeClient();
+ const imageUrl = "cindy-media://blobs/missing.png";
+ host.media = {
+ getCachedImage: async () => null,
+ cacheImage: async () => ({ absPath: "unused", url: imageUrl }),
+ resolveMediaUrl: vi.fn(() => null),
+ };
+ const im = new WecomIM(host, { clientFactory: () => client as never });
+
+ await im.init();
+ await im.commitFinal({
+ userId: "owner",
+ text: `done\n![missing](${imageUrl})`,
+ terminal: "done",
+ });
+
+ expect(client.uploadMedia).not.toHaveBeenCalled();
+ expect(client.sendMessage).toHaveBeenCalledWith("owner", {
+ msgtype: "markdown",
+ markdown: {
+ content: "done\n\n⚠️ 有 1 张图片未发送(图片已不存在或无法读取)。",
+ },
+ });
+ });
+
it("does not upload model-authored xdt-file links outside allowed roots", 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 73d323d76a..2892ef0fb3 100644
--- a/packages/lizi-im/src/wecom/index.ts
+++ b/packages/lizi-im/src/wecom/index.ts
@@ -270,6 +270,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {
userId: string,
absPath: string,
displayName?: string,
+ opts?: { threadTs?: string; usePendingFrame?: boolean },
): Promise<SendFileResult> {
let uploaded = false;
try {
@@ -281,7 +282,8 @@ export class WecomIM extends BaseIM implements TextChannelIM {
});
uploaded = true;
const lane = decodeWecomLane(userId);
- const frame = this.claimNewestFrame(userId);
+ const frame =
+ opts?.usePendingFrame === false ? null : this.claimNewestFrame(userId);
if (frame) {
try {
await client.replyMedia(frame, local.mediaType, result.media_id);
@@ -355,6 +357,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {
});
};
let rejectedFileCount = 0;
+ let unresolvedImageCount = 0;
for (const link of fileLinks) {
const resolved = await resolveAllowedWecomOutboundFile(
link.absPath,
@@ -372,6 +375,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {
if (absPath) {
addAttachment(absPath);
} else {
+ unresolvedImageCount += 1;
this.log.warn("failed to resolve terminal managed image", { url });
}
}
@@ -387,10 +391,14 @@ export class WecomIM extends BaseIM implements TextChannelIM {
const rejectedFileNotice = rejectedFileCount
? `⚠️ 有 ${rejectedFileCount} 个文件附件未发送(不在当前工作目录内或无法验证)。`
: "";
+ const unresolvedImageNotice = unresolvedImageCount
+ ? `⚠️ 有 ${unresolvedImageCount} 张图片未发送(图片已不存在或无法读取)。`
+ : "";
const visibleText = [
stripXdtFileLinks(stripXdtImageLinks(output.text)).trim(),
attachmentNotice,
rejectedFileNotice,
+ unresolvedImageNotice,
]
.filter(Boolean)
.join("\n\n");
@@ -404,6 +412,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {
output.userId,
attachment.absPath,
attachment.displayName,
+ { usePendingFrame: false },
);
if (!result.ok) {
failedAttachmentCount += 1;