Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(wecom): discard stale staged media
david9dcee1c86c0c
diff --git a/apps/desktop/src/main/cindy-media/__tests__/integrationCache.test.ts b/apps/desktop/src/main/cindy-media/__tests__/integrationCache.test.tsindex 3b92fd917a..995f71f93a 100644--- a/apps/desktop/src/main/cindy-media/__tests__/integrationCache.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/integrationCache.test.ts@@ -166,3 +166,22 @@ describe('miss 路径', () => {await expect(integrationCache.integrationCacheGet(KEY, db)).resolves.not.toBeNull();});});++describe('staged write rollback', () => {+ it('removes only the integration ref created by that write', async () => {+ const first = await integrationCache.integrationCachePut(+ { cacheKey: KEY, integration: 'feishu', buffer: BYTES_A, mimeType: 'image/png' },+ db,+ );+ const reused = await integrationCache.integrationCachePut(+ { cacheKey: KEY, integration: 'feishu', buffer: BYTES_A, mimeType: 'image/png' },+ db,+ );++ await reused.rollbackRef();+ expect(db.select().from(schema.mediaRefs).all()).toHaveLength(1);++ await first.rollbackRef();+ expect(db.select().from(schema.mediaRefs).all()).toHaveLength(0);+ });+});diff --git a/apps/desktop/src/main/cindy-media/integrationCache.ts b/apps/desktop/src/main/cindy-media/integrationCache.tsindex 0285daf544..7cd4d53a48 100644--- a/apps/desktop/src/main/cindy-media/integrationCache.ts+++ b/apps/desktop/src/main/cindy-media/integrationCache.ts@@ -55,6 +55,11 @@ export interface IntegrationCacheHit {hash: string;}+export interface IntegrationCacheWrite extends IntegrationCacheHit {+ /** Roll back only the integration-cache ref created by this write. */+ rollbackRef(): Promise<void>;+}+/** 查缓存:命中返回文件坐标并刷 LRU 时间;未登记 / 文件缺失(坏账)返回 null。 */export async function integrationCacheGet(cacheKey: string,@@ -98,7 +103,7 @@ export async function integrationCachePut(isCache?: boolean;},db?: LedgerDb,-): Promise<IntegrationCacheHit> {+): Promise<IntegrationCacheWrite> {const written = await ingestMedia({buffer: params.buffer,@@ -109,9 +114,10 @@ export async function integrationCachePut(db,);const existing = await ledger.getIntegrationCacheHash(params.cacheKey, db);+ let addedRefId: string | null = null;if (existing !== written.hash) {// 新登记 / token 复用换内容:追加索引行,cacheGet 取最新。- await ledger.addRef(+ addedRefId = await ledger.addRef({hash: written.hash,refKind: 'integration-cache',@@ -128,6 +134,9 @@ export async function integrationCachePut(absPath: resolved.absPath,mimeType: written.mimeType,hash: written.hash,+ rollbackRef: async () => {+ if (addedRefId) await ledger.removeRefById(addedRefId, db);+ },};}diff --git a/apps/desktop/src/main/cindy-media/ledger.ts b/apps/desktop/src/main/cindy-media/ledger.tsindex ae99192e2b..432d0798ce 100644--- a/apps/desktop/src/main/cindy-media/ledger.ts+++ b/apps/desktop/src/main/cindy-media/ledger.ts@@ -153,6 +153,12 @@ export async function addRef(params: AddRefParams, db: LedgerDb = defaultDb()):return id;}+/** Remove exactly one reference row created by a staged operation. */+export async function removeRefById(id: string, db: LedgerDb = defaultDb()): Promise<number> {+ const result = await db.delete(mediaRefs).where(eq(mediaRefs.id, id)).run();+ return result.changes;+}+/*** 集成缓存索引查询:cacheKey(`<集成名>:<token>`)→ 最近一次登记的指纹。* 同 key 多行(token 复用换内容)时取最新;无登记返回 null(调用方去真下载)。diff --git a/apps/desktop/src/main/im/host.ts b/apps/desktop/src/main/im/host.tsindex c37c60687e..aa0ccec30f 100644--- a/apps/desktop/src/main/im/host.ts+++ b/apps/desktop/src/main/im/host.ts@@ -95,13 +95,15 @@ const host: IMHost = {integration,buffer,mimeType,- // IM 入站媒体与图片同属不可再生的用户附件,不参与缓存回收。- isCache: false,+ // IM 入站媒体最终属于用户附件;在消息落库挂 session owner 前先按+ // 可回收暂存处理,失效账户只回滚本次新增的 cache ref。+ isCache: true,});return {absPath: hit.absPath,url: hit.url,mimeType: hit.mimeType,+ discard: hit.rollbackRef,};},getCachedImage: async (integration, token, options) => {diff --git a/packages/lizi-im/src/types.ts b/packages/lizi-im/src/types.tsindex a285c82829..92e43c4b7f 100644--- a/packages/lizi-im/src/types.ts+++ b/packages/lizi-im/src/types.ts@@ -100,7 +100,13 @@ export interface IMHostMediaCache {token: string;buffer: Uint8Array;mimeType: string;- }): Promise<{ absPath: string; url: string; mimeType: string }>;+ }): Promise<{+ absPath: string;+ url: string;+ mimeType: string;+ /** Release host-side staging when the originating account becomes stale. */+ discard?: () => Promise<void>;+ }>;/** 按 token 查已缓存图片;未缓存返回 null(调用方去真下载)。 */getCachedImage(integration: 'feishu' | 'discord' | 'telegram' | 'dingtalk' | 'wecom',diff --git a/packages/lizi-im/src/wecom/__tests__/index.test.ts b/packages/lizi-im/src/wecom/__tests__/index.test.tsindex 8fec851c45..a20653b9e1 100644--- a/packages/lizi-im/src/wecom/__tests__/index.test.ts+++ b/packages/lizi-im/src/wecom/__tests__/index.test.ts@@ -882,6 +882,64 @@ describe("WecomIM routing and ownership", () => {expect(cacheMedia).not.toHaveBeenCalled();});+ it("discards video 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();+ client.downloadFile.mockResolvedValueOnce({+ buffer: Buffer.from("video"),+ filename: "clip.mp4",+ });+ const staged = deferred<{+ absPath: string;+ url: string;+ mimeType: string;+ discard: () => Promise<void>;+ }>();+ const discard = vi.fn(async () => {});+ const cacheMedia = vi.fn(() => staged.promise);+ host.media = {+ cacheImage: vi.fn(),+ cacheMedia,+ getCachedImage: vi.fn(async () => null),+ 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.video", {+ body: {+ msgid: "stale-staged-video",+ aibotid: "bot-1",+ chattype: "single",+ from: { userid: "owner" },+ msgtype: "video",+ video: { url: "https://example.invalid/video" },+ },+ });+ await vi.waitFor(() => expect(cacheMedia).toHaveBeenCalledOnce());++ accountActive = false;+ staged.resolve({+ absPath: "C:\\managed\\clip.mp4",+ url: `cindy-media://blobs/${"a".repeat(64)}.mp4`,+ mimeType: "video/mp4",+ discard,+ });+ await vi.waitFor(() => expect(discard).toHaveBeenCalledOnce());++ expect(received).toEqual([]);+ });+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.tsindex 2892ef0fb3..2b7e4852c8 100644--- a/packages/lizi-im/src/wecom/index.ts+++ b/packages/lizi-im/src/wecom/index.ts@@ -674,6 +674,10 @@ export class WecomIM extends BaseIM implements TextChannelIM {buffer: downloaded.buffer,mimeType: mimeTypeForFilename(originalName),});+ if (!this.isCurrent(client, generation)) {+ await this.discardStagedMedia(stored.discard);+ return unsupportedPayload("video:stale", "视频下载已取消");+ }return {text: "",attachments: [@@ -686,6 +690,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {},],unsupported: [],+ discard: stored.discard,};} catch (error) {this.log.warn("failed to stage inbound video", safeError(error));@@ -702,6 +707,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {text: string;attachments: IMAttachment[];unsupported: IMUnsupportedEntry[];+ discard?: () => Promise<void>;}>,): Promise<void> {if (!this.isCurrent(client, generation)) return;@@ -724,7 +730,10 @@ export class WecomIM extends BaseIM implements TextChannelIM {this.log.warn("failed to normalize inbound message", safeError(error));normalized = unsupportedPayload(body.msgtype, `${body.msgtype} 处理失败`);}- if (!this.isCurrent(client, generation)) return;+ if (!this.isCurrent(client, generation)) {+ await this.discardStagedMedia(normalized.discard);+ return;+ }const quoted = quoteContext(body);const event: IMMessageEvent = {@@ -757,6 +766,15 @@ export class WecomIM extends BaseIM implements TextChannelIM {for (const handler of this.messageHandlers) handler(event);}+ private async discardStagedMedia(discard?: () => Promise<void>): Promise<void> {+ if (!discard) return;+ try {+ await discard();+ } catch (error) {+ this.log.warn("failed to discard stale inbound media", safeError(error));+ }+ }+private async acceptOwner(body: BaseMessage): Promise<boolean> {const sender = body.from.userid.trim();if (!sender) return false;