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): address review feedback

davideddbe88f9cab
diff --git a/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts b/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts
index 9ec742055e..b16462b22d 100644
--- a/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts
+++ b/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts
@@ -210,6 +210,32 @@ describe('WeCom group notification security boundary', () => {
expect(secrets.write).not.toHaveBeenCalled();
});
+ it('does not resurrect a webhook save that was queued before clear', async () => {
+ let releasePublish: (() => void) | undefined;
+ const existingUrl = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=existing';
+ const replacementUrl = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=replacement';
+ const fetchImpl = vi.fn(async () => {
+ await new Promise<void>((resolve) => {
+ releasePublish = resolve;
+ });
+ return response({ errcode: 0, errmsg: 'ok' });
+ });
+ const secrets = createSecrets(existingUrl, 'true');
+ const service = new WecomGroupNotificationService(fetchImpl, secrets);
+
+ const publishing = service.publishMarkdown('blocking publish');
+ const saving = service.saveAndTest(replacementUrl, 'Localized test message');
+ await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledOnce());
+
+ expect(service.clear()).toEqual({ configured: false, enabled: false });
+ releasePublish?.();
+
+ await expect(publishing).resolves.toBeUndefined();
+ await expect(saving).rejects.toThrow('WECOM_GROUP_CONFIG_CHANGED');
+ expect(fetchImpl).toHaveBeenCalledOnce();
+ expect(service.getState()).toEqual({ configured: false, enabled: false });
+ });
+
it('rejects redirects instead of following a changed destination', async () => {
const fetchImpl = vi.fn(
async () =>
diff --git a/apps/desktop/src/main/im/host.ts b/apps/desktop/src/main/im/host.ts
index aa0ccec30f..9c4448112e 100644
--- a/apps/desktop/src/main/im/host.ts
+++ b/apps/desktop/src/main/im/host.ts
@@ -76,18 +76,21 @@ const host: IMHost = {
// cindy-media 媒体总仓回调(规则 25):IM 入站图片按平台 token
// 免重下、内容寻址去重、isCache=true 吃缓存回收策略;包侧只摸字节和字符串。
media: {
- cacheImage: async ({ integration, token, buffer, mimeType }) => {
+ cacheImage: async ({ integration, token, buffer, mimeType, staging }) => {
const hit = await integrationCachePut({
cacheKey: integrationCacheKey(integration, token),
integration,
buffer,
mimeType,
- // IM 入站图是**用户附件**不是可再生缓存(review P1):discord CDN 地址
- // 限时签名,被缓存 LRU 逐出后无法重下 = 弄丢用户的图。isCache=false +
- // 落库挂 session-attachment 引用,与桌面粘贴附件同生命周期。
- isCache: false,
+ // 常规入站图直接按用户附件保存;需要跨账户竞态保护的 transport 可先
+ // 以可回收 staging 写入,确认归属后由消息落库的 pinBlob 提升为用户附件。
+ isCache: staging === true,
});
- return { absPath: hit.absPath, url: hit.url };
+ return {
+ absPath: hit.absPath,
+ url: hit.url,
+ ...(staging ? { discard: hit.rollbackRef } : {}),
+ };
},
cacheMedia: async ({ integration, token, buffer, mimeType }) => {
const hit = await integrationCachePut({
diff --git a/apps/desktop/src/main/im/wecom/__tests__/uiText.test.ts b/apps/desktop/src/main/im/wecom/__tests__/uiText.test.ts
new file mode 100644
index 0000000000..d09f153b00
--- /dev/null
+++ b/apps/desktop/src/main/im/wecom/__tests__/uiText.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from 'vitest';
+
+import { ui } from '../uiText';
+
+describe('WeCom UI text', () => {
+ it('uses 任务 for session-level actions and 对话 for the chat channel', () => {
+ expect(ui.slash.new).toContain('新任务');
+ expect(ui.slash.help).toContain('/new 开始新任务');
+ expect(ui.slash.detachedBySlash).toContain('企业微信对话');
+ expect(ui.cards.control.sessionPickerHint).toContain('选择任务、创建新任务');
+ expect(ui.cards.control.newSessionWelcomePrompts[0]?.('工作区')).toContain('创建新任务');
+ });
+});
diff --git a/apps/desktop/src/main/im/wecom/uiText.ts b/apps/desktop/src/main/im/wecom/uiText.ts
index 291100fb4e..fb8bc6334a 100644
--- a/apps/desktop/src/main/im/wecom/uiText.ts
+++ b/apps/desktop/src/main/im/wecom/uiText.ts
@@ -4,10 +4,10 @@ import type { ImUiTextPack } from '../shared/types';
export const ui = {
slash: {
- new: '🌱 新对话已开始,之前的上下文已清空。',
+ new: '🌱 新任务已开始,之前的上下文已清空。',
help: `🤖 可用命令:
-/new 开始新对话
+/new 开始新任务
/stop 中止当前任务
/exctr 结束已有接管
/help 查看帮助
@@ -15,9 +15,9 @@ export const ui = {
任务运行中可发送 \`!stop\` 中止当前任务并清空排队消息。`,
unknownCommand: (cmd: string) =>
`未识别命令 \`${cmd}\`。可用命令:/new、/stop、/exctr、/help`,
- detachedBySlash: '🚪 已结束接管,后续消息回到企业微信会话。',
- detachedByRevoke: '⚠️ desktop 端已收回接管,后续消息回到企业微信会话。',
- notAttached: '当前没有正在接管的会话。',
+ detachedBySlash: '🚪 已结束接管,后续消息回到企业微信对话。',
+ detachedByRevoke: '⚠️ desktop 端已收回接管,后续消息回到企业微信对话。',
+ notAttached: '当前没有正在接管的任务。',
},
agent: {
completedNoText: '✅ 任务已完成(本轮没有文本输出)',
@@ -34,10 +34,10 @@ export const ui = {
: missing === 'provider-disconnected'
? '连接已断开或失效'
: `需要先登录 ${agentKind}`;
- const message = `⚠️ 当前企业微信会话使用「${provider}」(${model}),${reason}。`;
+ const message = `⚠️ 当前企业微信对话使用「${provider}」(${model}),${reason}。`;
return attached
? `${message}\n请在 desktop 修复认证后继续发送消息。`
- : `${message}\n修改后请发送 \`/new\` 开始新会话。`;
+ : `${message}\n修改后请发送 \`/new\` 开始新任务。`;
},
controlInProgress: '🎮 接管选择尚未完成,请先处理上一条交互消息。',
credentialBusy: '⏳ 本地 Agent 正在运行,暂时不能切换凭证模式,请稍后重试。',
@@ -108,30 +108,30 @@ export const ui = {
},
control: {
title: '🎮 选择工作区',
- emptyBody: '_暂时没有可接管的工作区,请先在 desktop 创建会话。_',
+ emptyBody: '_暂时没有可接管的工作区,请先在 desktop 创建任务。_',
hint: '选择工作区继续,或退出本次操作。',
attachedSwitchHint: (sessionTitle: string) => `当前正在接管:**${sessionTitle}**`,
btnExit: '🚪 退出',
resolvedExit: '🚪 已退出接管',
- sessionPickerTitle: (displayName: string) => `🎮 ${displayName} 中的会话`,
- sessionPickerHint: '选择会话、创建新会话或返回上一步。',
- sessionPickerEmptyBody: (displayName: string) => `_${displayName} 中暂时没有可用会话。_`,
+ sessionPickerTitle: (displayName: string) => `🎮 ${displayName} 中的任务`,
+ sessionPickerHint: '选择任务、创建新任务或返回上一步。',
+ sessionPickerEmptyBody: (displayName: string) => `_${displayName} 中暂时没有可用任务。_`,
btnNew: '➕ 新建',
btnBack: '↩️ 返回',
resolvedSessionPick: (sessionTitle: string, workspaceName: string) =>
`🎯 已接管 **${sessionTitle}**(${workspaceName})`,
- resolvedNewSession: (workspaceName: string) => `✨ 已在 **${workspaceName}** 新建并接管会话`,
+ resolvedNewSession: (workspaceName: string) => `✨ 已在 **${workspaceName}** 新建并接管任务`,
attachFailed: (reason: string) => `❌ 接管失败:${reason}`,
- sessionBusyOldCardPlaceholder: '⏳ 该会话仍在运行,请稍后重试。',
+ sessionBusyOldCardPlaceholder: '⏳ 该任务仍在运行,请稍后重试。',
sessionBusyPrompts: [
(sessionTitle: string) => `⏳ **${sessionTitle}** 正在运行,请等待当前回合结束。`,
],
takeoverLoadingPrompts: [(sessionTitle: string) => `⏳ 正在接管 **${sessionTitle}**…`],
sessionAttachedOneshotPrompts: [
- '我已从企业微信接管此会话。请简要同步当前进度,并询问下一步指令。',
+ '我已从企业微信接管此任务。请简要同步当前进度,并询问下一步指令。',
],
newSessionWelcomePrompts: [
- (workspaceName: string) => `✨ 已在 **${workspaceName}** 创建新会话,可以发送第一条指令。`,
+ (workspaceName: string) => `✨ 已在 **${workspaceName}** 创建新任务,可以发送第一条指令。`,
],
},
},
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/notifier.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/notifier.test.ts
index 4e83c86db7..c0a4ed8c8c 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/notifier.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/notifier.test.ts
@@ -197,4 +197,27 @@ describe('DesktopNotifier desktop status mapping', () => {
expect(warn).toHaveBeenCalledWith('WeCom group notify failed', sendError);
expect(sendMobileSessionNotify).not.toHaveBeenCalled();
});
+
+ it('does not expose local attachment references in WeCom group notifications', async () => {
+ const { notifier, publishMarkdown } = createNotifier();
+ const groupSchedule = {
+ ...schedule,
+ notify: { desktop: false, feishu: false, wecomGroup: true },
+ } as Schedule;
+
+ await notifier.notify(groupSchedule, {
+ ...run('success'),
+ resultText: [
+ '检查完成',
+ '[报告](xdt-file:///C:/private/report.txt)',
+ '![截图](cindy-media://blobs/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.png)',
+ ].join('\n'),
+ });
+
+ const published = String(publishMarkdown.mock.calls[0]?.[0]);
+ expect(published).toContain('检查完成');
+ expect(published).not.toContain('xdt-file://');
+ expect(published).not.toContain('cindy-media://');
+ expect(published).not.toContain('C:/private/report.txt');
+ });
});
diff --git a/apps/desktop/src/main/scheduler-host/notifier.ts b/apps/desktop/src/main/scheduler-host/notifier.ts
index b65aeb923d..ff76483310 100644
--- a/apps/desktop/src/main/scheduler-host/notifier.ts
+++ b/apps/desktop/src/main/scheduler-host/notifier.ts
@@ -12,7 +12,7 @@
import type { BrowserWindow } from 'electron';
import type { Notifier, Schedule, ScheduleRun } from '@cindy/maker-scheduler';
-import type { FeishuIM } from '@cindy/im';
+import { stripXdtFileLinks, stripXdtImageLinks, type FeishuIM } from '@cindy/im';
import type { Logger } from '@cindy/maker-scheduler';
@@ -139,7 +139,8 @@ function renderExternalMessage(schedule: Schedule, run: ScheduleRun): string {
// 完整内容用户可点 "Open session" 看。上限 6000:多 PR 审查汇总这类逐行带
// markdown 链接的正文 1500 会拦腰截断;6000 即使全 CJK(~18KB UTF-8)也在
// 飞书互动卡片 30KB 体积上限内。
- lines.push('', truncate(run.resultText, 6000));
+ const safeResultText = stripXdtFileLinks(stripXdtImageLinks(run.resultText)).trim();
+ if (safeResultText) lines.push('', truncate(safeResultText, 6000));
}
// ── 元信息行(时间 / 耗时 / agent / cwd)────────────────────────────────
diff --git a/apps/desktop/src/main/wecomGroupNotification.ts b/apps/desktop/src/main/wecomGroupNotification.ts
index e970bcc6c2..bd84548e69 100644
--- a/apps/desktop/src/main/wecomGroupNotification.ts
+++ b/apps/desktop/src/main/wecomGroupNotification.ts
@@ -124,6 +124,7 @@ async function readResponseText(response: Response): Promise<string> {
export class WecomGroupNotificationService implements WecomGroupNotificationPublisher {
private publishTail: Promise<void> = Promise.resolve();
+ private configGeneration = 0;
constructor(
private readonly fetchImpl: FetchLike = (input, init) => net.fetch(input, init),
@@ -148,6 +149,7 @@ export class WecomGroupNotificationService implements WecomGroupNotificationPubl
}
setEnabled(enabled: boolean): WecomGroupNotificationState {
+ this.configGeneration += 1;
const state = this.getState();
if (!state.configured) throw new Error('WECOM_GROUP_WEBHOOK_NOT_CONFIGURED');
if (!this.secrets.write(ENABLED_SETTING_NAME, String(enabled))) {
@@ -163,13 +165,20 @@ export class WecomGroupNotificationService implements WecomGroupNotificationPubl
): Promise<WecomGroupNotificationState> {
const url = parseWebhookUrl(rawUrl);
const message = parseTestMessage(testMessage);
+ const configGeneration = (this.configGeneration += 1);
await this.enqueue(() => {
if (!isAccountCurrent()) throw new ImAccountScopeClosedError();
+ if (configGeneration !== this.configGeneration) {
+ throw new Error('WECOM_GROUP_CONFIG_CHANGED');
+ }
return this.send(url, message);
});
if (!isAccountCurrent()) {
throw new ImAccountScopeClosedError();
}
+ if (configGeneration !== this.configGeneration) {
+ throw new Error('WECOM_GROUP_CONFIG_CHANGED');
+ }
const previousUrl = this.secrets.read(WEBHOOK_SECRET_NAME);
const previousEnabled = this.secrets.read(ENABLED_SETTING_NAME);
const saved =
@@ -193,6 +202,7 @@ export class WecomGroupNotificationService implements WecomGroupNotificationPubl
}
clear(): WecomGroupNotificationState {
+ this.configGeneration += 1;
this.secrets.remove(WEBHOOK_SECRET_NAME);
this.secrets.remove(ENABLED_SETTING_NAME);
return { configured: false, enabled: false };
diff --git a/apps/desktop/src/renderer/components/settings/WecomBotSection.tsx b/apps/desktop/src/renderer/components/settings/WecomBotSection.tsx
index c443e62d00..31aa001a41 100644
--- a/apps/desktop/src/renderer/components/settings/WecomBotSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/WecomBotSection.tsx
@@ -249,6 +249,26 @@ export function WecomBotSection({
: t('settings.wecomBot.connect')}
</button>
)}
+ {botId.trim() ? (
+ <button
+ type="button"
+ onClick={() => void handleDisconnect()}
+ disabled={isDisconnecting}
+ className={cn(
+ 'flex h-[42px] flex-1 items-center justify-center gap-1.5 rounded-full',
+ 'border border-[var(--settings-btn-secondary-border)] bg-[var(--settings-btn-secondary-bg)]',
+ 'text-13 font-medium text-[var(--settings-btn-secondary-text)]',
+ isDisconnecting && 'cursor-not-allowed opacity-40',
+ )}
+ >
+ {isDisconnecting ? (
+ <Loader2 size={13} className="animate-spin" />
+ ) : (
+ <Trash2 size={13} />
+ )}
+ {t('settings.wecomBot.disconnect')}
+ </button>
+ ) : null}
</div>
</div>
)}
diff --git a/packages/lizi-im/src/index.ts b/packages/lizi-im/src/index.ts
index 62b6300cb8..74f116d1bf 100644
--- a/packages/lizi-im/src/index.ts
+++ b/packages/lizi-im/src/index.ts
@@ -51,6 +51,7 @@ export {
chunkWecomMarkdown,
escapeWecomMarkdown,
} from './wecom/codec.js';
+export { stripXdtFileLinks, stripXdtImageLinks } from './xdtRefs.js';
export {
decodeLaneUserId as decodeTelegramLaneUserId,
encodeLaneUserId as encodeTelegramLaneUserId,
diff --git a/packages/lizi-im/src/types.ts b/packages/lizi-im/src/types.ts
index 92e43c4b7f..ec77420b87 100644
--- a/packages/lizi-im/src/types.ts
+++ b/packages/lizi-im/src/types.ts
@@ -90,7 +90,9 @@ export interface IMHostMediaCache {
token: string;
buffer: Uint8Array;
mimeType: string;
- }): Promise<{ absPath: string; url: string }>;
+ /** Keep the blob reclaimable until the transport confirms account ownership after the write. */
+ staging?: boolean;
+ }): Promise<{ absPath: string; url: string; discard?: () => Promise<void> }>;
/**
* 其它 Cindy 托管媒体入总仓。未提供时 transport 必须降级为 unsupported,
* 不得新增写入冻结的 `cc-agent/*-media` 历史目录。
diff --git a/packages/lizi-im/src/wecom/__tests__/codec.test.ts b/packages/lizi-im/src/wecom/__tests__/codec.test.ts
index 10845b359a..ae22e11903 100644
--- a/packages/lizi-im/src/wecom/__tests__/codec.test.ts
+++ b/packages/lizi-im/src/wecom/__tests__/codec.test.ts
@@ -23,6 +23,13 @@ describe("WeCom lane codec", () => {
targetId: "zhangsan",
});
});
+
+ it.each(["group/", "group/abc=", "group/abc+", "group/abc/", "group/_w"])(
+ "rejects malformed group lane %s",
+ (lane) => {
+ expect(() => decodeWecomLane(lane)).toThrow("WECOM_GROUP_LANE_INVALID");
+ },
+ );
});
describe("WeCom markdown chunking", () => {
diff --git a/packages/lizi-im/src/wecom/__tests__/index.test.ts b/packages/lizi-im/src/wecom/__tests__/index.test.ts
index a20653b9e1..08d47a0b23 100644
--- a/packages/lizi-im/src/wecom/__tests__/index.test.ts
+++ b/packages/lizi-im/src/wecom/__tests__/index.test.ts
@@ -297,7 +297,7 @@ describe("WecomIM routing and ownership", () => {
);
await flush();
await im.beginReply("owner");
- now += 5 * 60_000;
+ now += 3 * 60_000;
await im.commitFinal({
userId: "owner",
@@ -465,9 +465,11 @@ describe("WecomIM routing and ownership", () => {
secrets.set("wecom-owner-user-id", "owner");
const client = new FakeClient();
const im = new WecomIM(host, { clientFactory: () => client as never });
- vi.spyOn(im, "sendFile").mockResolvedValue({
- ok: false,
- reason: "UPLOAD_FAIL",
+ const nextFrame = message({ id: "m-next", sender: "owner", text: "next" });
+ vi.spyOn(im, "sendFile").mockImplementation(async () => {
+ client.emit("message.text", nextFrame);
+ await flush();
+ return { ok: false, reason: "UPLOAD_FAIL" };
});
await im.init();
@@ -486,6 +488,14 @@ describe("WecomIM routing and ownership", () => {
msgtype: "markdown",
markdown: { content: "⚠️ 有 1 个附件发送失败,请稍后重试。" },
});
+
+ await im.sendMarkdownText("owner", "next reply");
+ expect(client.replyStream).toHaveBeenLastCalledWith(
+ nextFrame,
+ expect.any(String),
+ "next reply",
+ true,
+ );
});
it("deduplicates repeated callback message ids", async () => {
@@ -703,6 +713,60 @@ describe("WecomIM routing and ownership", () => {
expect(cacheImage).not.toHaveBeenCalled();
});
+ it("discards image staging when the owning account closes during the write", 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 staged = deferred<{
+ absPath: string;
+ url: string;
+ discard: () => Promise<void>;
+ }>();
+ const discard = vi.fn(async () => {});
+ const cacheImage = vi.fn(() => staged.promise);
+ host.media = {
+ getCachedImage: vi.fn(async () => null),
+ cacheImage,
+ resolveMediaUrl: vi.fn(() => null),
+ };
+ const im = new WecomIM(host, { clientFactory: () => client as never });
+ const received: IMMessageEvent[] = [];
+ im.onMessage((event) => received.push(event));
+
+ await im.init();
+ client.emit("message.image", {
+ body: {
+ msgid: "stale-staged-image",
+ aibotid: "bot-1",
+ chattype: "single",
+ from: { userid: "owner" },
+ msgtype: "image",
+ image: { url: "https://example.invalid/image" },
+ },
+ });
+ await vi.waitFor(() => expect(cacheImage).toHaveBeenCalledOnce());
+ expect(cacheImage).toHaveBeenCalledWith(
+ expect.objectContaining({ staging: true }),
+ );
+
+ accountActive = false;
+ staged.resolve({
+ absPath: "C:\\managed\\photo.jpg",
+ url: "cindy-media://image",
+ discard,
+ });
+ await vi.waitFor(() => expect(discard).toHaveBeenCalledOnce());
+
+ expect(received).toEqual([]);
+ });
+
it("does not pin or download a cached image after the owning account boundary closes", async () => {
const { host, secrets } = createHost();
secrets.set("wecom-owner-user-id", "owner");
diff --git a/packages/lizi-im/src/wecom/__tests__/media.test.ts b/packages/lizi-im/src/wecom/__tests__/media.test.ts
index 5265634234..1db9b7cee6 100644
--- a/packages/lizi-im/src/wecom/__tests__/media.test.ts
+++ b/packages/lizi-im/src/wecom/__tests__/media.test.ts
@@ -53,6 +53,23 @@ describe("WeCom media helpers", () => {
expect(stored.mimeType).toBe("text/plain");
});
+ it("removes a staged download when ownership changes during the write", async () => {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cindy-wecom-"));
+ tempDirs.push(dir);
+ let checks = 0;
+
+ await expect(
+ persistWecomDownload({
+ mediaDir: dir,
+ buffer: Buffer.from("stale"),
+ filename: "stale.txt",
+ shouldKeep: () => (checks += 1) === 1,
+ }),
+ ).rejects.toThrow("WECOM_MEDIA_STALE");
+
+ expect(await fs.readdir(dir)).toEqual([]);
+ });
+
it("selects outbound media types from safe metadata", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cindy-wecom-"));
tempDirs.push(dir);
diff --git a/packages/lizi-im/src/wecom/codec.ts b/packages/lizi-im/src/wecom/codec.ts
index 1011750884..79d5a07cbf 100644
--- a/packages/lizi-im/src/wecom/codec.ts
+++ b/packages/lizi-im/src/wecom/codec.ts
@@ -17,10 +17,21 @@ export function decodeWecomLane(userId: string): WecomLane {
return { kind: "single", targetId: userId };
}
const encoded = userId.slice(GROUP_LANE_PREFIX.length);
- if (!encoded) throw new Error("WECOM_GROUP_LANE_INVALID");
- const targetId = Buffer.from(encoded, "base64url").toString("utf8");
- if (!targetId) throw new Error("WECOM_GROUP_LANE_INVALID");
- return { kind: "group", targetId };
+ if (!encoded || !/^[A-Za-z0-9_-]+$/.test(encoded)) {
+ throw new Error("WECOM_GROUP_LANE_INVALID");
+ }
+ try {
+ const targetId = Buffer.from(encoded, "base64url").toString("utf8");
+ if (
+ !targetId ||
+ Buffer.from(targetId, "utf8").toString("base64url") !== encoded
+ ) {
+ throw new Error("WECOM_GROUP_LANE_INVALID");
+ }
+ return { kind: "group", targetId };
+ } catch {
+ throw new Error("WECOM_GROUP_LANE_INVALID");
+ }
}
export function chunkWecomMarkdown(source: string): string[] {
diff --git a/packages/lizi-im/src/wecom/index.ts b/packages/lizi-im/src/wecom/index.ts
index 2b7e4852c8..ab52a5786b 100644
--- a/packages/lizi-im/src/wecom/index.ts
+++ b/packages/lizi-im/src/wecom/index.ts
@@ -49,7 +49,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 STREAM_SAFE_TIMEOUT_MS = 2 * 60_000 + 45_000;
const DEDUPE_CAPACITY = 2_048;
const MAX_TERMINAL_ATTACHMENTS = 4;
const SECRET_WRITE_FAILED_REASON = "无法使用系统安全存储保存企业微信机器人凭证";
@@ -423,9 +423,12 @@ export class WecomIM extends BaseIM implements TextChannelIM {
}
if (failedAttachmentCount > 0) {
try {
- await this.sendMarkdownText(
+ await this.sendChunks(
output.userId,
- `⚠️ 有 ${failedAttachmentCount} 个附件发送失败,请稍后重试。`,
+ chunkWecomMarkdown(
+ `⚠️ 有 ${failedAttachmentCount} 个附件发送失败,请稍后重试。`,
+ ),
+ "none",
);
} catch (error) {
this.log.warn(
@@ -637,6 +640,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {
mediaDir: this.mediaDir,
buffer: downloaded.buffer,
filename: downloaded.filename,
+ shouldKeep: () => this.isCurrent(client, generation),
});
return {
text: "",
@@ -828,7 +832,12 @@ export class WecomIM extends BaseIM implements TextChannelIM {
token,
buffer: downloaded.buffer,
mimeType,
+ staging: true,
});
+ if (!this.isCurrent(client, generation)) {
+ await this.discardStagedMedia(stored.discard);
+ return null;
+ }
return {
kind: "image",
absPath: stored.absPath,
@@ -842,6 +851,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {
buffer: downloaded.buffer,
filename,
fallbackExtension: ".jpg",
+ shouldKeep: () => this.isCurrent(client, generation),
});
return { kind: "image", ...persisted };
} catch (error) {
@@ -853,15 +863,17 @@ export class WecomIM extends BaseIM implements TextChannelIM {
private async sendChunks(
userId: string,
chunks: string[],
- framePreference: "newest" | "oldest" = "newest",
+ framePreference: "newest" | "oldest" | "none" = "newest",
): Promise<{ messageId: string }> {
const client = this.requireConnectedClient();
const lane = decodeWecomLane(userId);
const firstId = randomUUID();
const frame =
- framePreference === "oldest"
- ? this.claimOldestFrame(userId)
- : this.claimNewestFrame(userId);
+ framePreference === "none"
+ ? null
+ : framePreference === "oldest"
+ ? this.claimOldestFrame(userId)
+ : this.claimNewestFrame(userId);
let start = 0;
if (frame) {
diff --git a/packages/lizi-im/src/wecom/media.ts b/packages/lizi-im/src/wecom/media.ts
index fba0d9d611..f6351a5a1f 100644
--- a/packages/lizi-im/src/wecom/media.ts
+++ b/packages/lizi-im/src/wecom/media.ts
@@ -124,6 +124,7 @@ export async function persistWecomDownload(args: {
buffer: Buffer;
filename?: string;
fallbackExtension?: string;
+ shouldKeep?: () => boolean;
}): Promise<{ absPath: string; originalName: string; mimeType: string }> {
if (args.buffer.length === 0) throw new Error("WECOM_MEDIA_EMPTY");
if (args.buffer.length > MAX_MEDIA_BYTES)
@@ -131,9 +132,14 @@ export async function persistWecomDownload(args: {
const originalName = safeWecomFilename(args.filename, args.fallbackExtension);
const storageName = `${randomUUID()}-${originalName}`;
+ if (args.shouldKeep?.() === false) throw new Error("WECOM_MEDIA_STALE");
await fs.mkdir(args.mediaDir, { recursive: true });
const absPath = path.join(args.mediaDir, storageName);
await fs.writeFile(absPath, args.buffer, { flag: "wx" });
+ if (args.shouldKeep?.() === false) {
+ await fs.rm(absPath, { force: true });
+ throw new Error("WECOM_MEDIA_STALE");
+ }
return {
absPath,
originalName,