Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 切换账号与非当前群删除时回收群聊发件箱的暂存附件
Dashf504d4a22975
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsxindex 0be6c44dcd..5182d4c788 100644--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx@@ -229,6 +229,8 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {},);} else if (result.errorCode === 'NOT_FOUND') {+ // Gone for this account (deleted, archived or left): nothing of it is left to send.+ discardBotGroupOutbox(groupId);setState({ kind: 'missing' });} else {// Keep a timeline that is already on screen; only a first read fails loudly.diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsxindex 7dbbeae86f..9b780a3001 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx@@ -13,7 +13,7 @@ import { FeatureSidebarSlotProvider, useFeatureContentHeader } from '../../featuimport { markBotRead, getBotLastReadAt, botGroupReadKey, resetBotReadStateForTests } from '../botReadState';import { botGroupAttachmentScope } from '../botGroupAttachments';import { getBotGroupListSnapshot, refreshBotGroups, resetBotGroupStoreForTests } from '../botGroupStore';-import { resetBotGroupOutboxForTests } from '../botGroupOutbox';+import { getBotGroupOutbox, resetBotGroupOutboxForTests } from '../botGroupOutbox';import { BotGroupChatView } from '../BotGroupChatView';import { ControlledBanner, __resetControlledBannerForTests } from '../../remote-device/ControlledBanner';import type {@@ -1382,6 +1382,20 @@ describe('BotGroupChatView', () => {expect(mocks.sendBotGroupMessage.mock.calls[1]![0].clientId).toBe(mocks.sendBotGroupMessage.mock.calls[0]![0].clientId);});+ it('drops the outbox of a group that reads as gone', async () => {+ renderView();+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;+ mocks.sendBotGroupMessage.mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' });+ fireEvent.change(input, { target: { value: '没发出去' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ fireEvent.change(input, { target: { value: '正在写' } });+ await waitFor(() => expect(getBotGroupOutbox('g1').map((entry) => entry.status)).toEqual(['failed']));+ mocks.getBotGroup.mockResolvedValue({ ok: false, errorCode: 'NOT_FOUND', message: '' });+ pushMessages();+ expect(await screen.findByText('bots.groupChat.unavailableTitle')).toBeTruthy();+ expect(getBotGroupOutbox('g1')).toEqual([]);+ });+it('keeps a late receipt out of the next group and shows the message when coming back', async () => {const send = pendingSend();const view = renderView();diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botGroupOutbox.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botGroupOutbox.test.tsindex 4bac65e98b..1a5717fef0 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botGroupOutbox.test.ts+++ b/apps/desktop/src/renderer/features/bots/__tests__/botGroupOutbox.test.ts@@ -32,6 +32,9 @@ const mocks = vi.hoisted(() => ({materialize: vi.fn(async (files: readonly AttachedFile[]) => [...files]),protectedUrls: [] as string[],cleanupStaged: vi.fn(),+ getBotGroup: vi.fn(),+ list: { groups: [] as Array<{ id: string }>, loaded: false },+ listListeners: new Set<() => void>(),}));vi.mock('@/contexts/dataOwnerGeneration', () => ({@@ -39,8 +42,19 @@ vi.mock('@/contexts/dataOwnerGeneration', () => ({isDataOwnerGenerationCurrent: (owner: number) => owner === mocks.owner,}));vi.mock('../botGroupStore', () => ({- botGroupApi: () => ({ sendBotGroupMessage: mocks.send }),+ botGroupApi: () => ({ sendBotGroupMessage: mocks.send, getBotGroup: mocks.getBotGroup }),+ getBotGroupListSnapshot: () => mocks.list,+ subscribeBotGroups: (listener: () => void) => {+ mocks.listListeners.add(listener);+ return () => mocks.listListeners.delete(listener);+ },}));++/** The sidebar list re-read: these groups exist for the account. */+function listGroups(ids: string[]) {+ mocks.list = { groups: ids.map((id) => ({ id })), loaded: true };+ for (const listener of [...mocks.listListeners]) listener();+}vi.mock('@/lib/annotationBurnIn', () => ({isAnnotationBurnInError: () => false,materializeAnnotatedAttachmentsForSend: (files: readonly AttachedFile[]) => mocks.materialize(files),@@ -129,6 +143,8 @@ beforeEach(() => {mocks.materialize.mockReset().mockImplementation(async (files: readonly AttachedFile[]) => [...files]);mocks.protectedUrls = [];mocks.cleanupStaged.mockReset();+ mocks.getBotGroup.mockReset().mockResolvedValue({ ok: true, group: {} });+ mocks.list = { groups: [], loaded: false };resetBotGroupOutboxForTests();});@@ -552,4 +568,94 @@ describe('botGroupOutbox', () => {expect(getBotGroupOutbox('g1')).toEqual([]);});});++ describe('staged files of messages that never went out', () => {+ const staged = (id: string) =>+ ({ id, name: `${id}.txt`, path: `/staged/${id}.bin`, size: 1, category: 'text', mimeType: 'text/plain', type: 'file' }) as unknown as AttachedFile;+ const released = () => mocks.cleanupStaged.mock.calls.map(([files]) => (files as AttachedFile[]).map((file) => file.id).join(','));++ it('on an account switch: releases queued and failed sends, settles the one in flight by its answer', async () => {+ const inFlight = deferred();+ mocks.send.mockResolvedValueOnce({ ok: true, messageId: 'm-sent' })+ .mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' })+ .mockReturnValueOnce(inFlight.promise);+ enqueueBotGroupSend(draft({ clientId: 'sent' }, { files: [staged('sent')] }));+ enqueueBotGroupSend(draft({ clientId: 'failed' }, { files: [staged('failed')] }));+ enqueueBotGroupSend(draft({ clientId: 'flying' }, { files: [staged('flying')] }));+ enqueueBotGroupSend(draft({ clientId: 'queued' }, { files: [staged('queued')] }));+ await flush();+ expect(mocks.send).toHaveBeenCalledTimes(3);++ mocks.owner = 2;+ expect(getBotGroupOutbox('g1')).toEqual([]);+ expect(released()).toEqual(['failed']);+ // The in-flight send went out after all: its file stays with the message.+ inFlight.resolve({ ok: true, messageId: 'm-late' });+ await flush();+ // The queued one never reached main; nothing is sent under the new account.+ expect(mocks.send).toHaveBeenCalledTimes(3);+ expect(released()).toEqual(['failed', 'queued']);+ });++ it('on an account switch: releases an in-flight send that did not go out, and one still burning in', async () => {+ const inFlight = deferred();+ let finishBurn!: (files: AttachedFile[]) => void;+ mocks.send.mockReturnValueOnce(inFlight.promise);+ enqueueBotGroupSend(draft({ groupId: 'g1', clientId: 'flying' }, { files: [staged('flying')] }));+ const drawn = { ...staged('drawn'), category: 'image', annotationStrokes: [{ points: [{ x: 1, y: 1 }] }] } as unknown as AttachedFile;+ mocks.materialize.mockImplementationOnce(() => new Promise((resolve) => { finishBurn = resolve; }));+ enqueueBotGroupSend(draft({ groupId: 'g2', clientId: 'burning' }, { files: [drawn] }));+ await flush();+ mocks.owner = 2;+ getBotGroupOutbox('g1');+ inFlight.resolve({ ok: false, errorCode: 'INTERNAL', message: '' });+ finishBurn([drawn]);+ await flush();+ expect(released().sort()).toEqual(['drawn', 'flying']);+ // The burn finished under the new account: the old message is never sent.+ expect(mocks.send).toHaveBeenCalledTimes(1);+ });++ it('discards a group that left the list once a read confirms it is gone, including late answers', async () => {+ const late = deferred();+ mocks.send.mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' }).mockReturnValueOnce(late.promise);+ enqueueBotGroupSend(draft({ groupId: 'gone', clientId: 'failed' }, { files: [staged('failed')] }));+ enqueueBotGroupSend(draft({ groupId: 'gone', clientId: 'flying' }, { files: [staged('flying')] }));+ enqueueBotGroupSend(draft({ groupId: 'kept', clientId: 'other' }, { files: [staged('other')] }));+ await flush();+ mocks.getBotGroup.mockImplementation(async (groupId: string) =>+ groupId === 'gone' ? { ok: false, errorCode: 'NOT_FOUND', message: '' } : { ok: true, group: {} });+ // `kept` is missing from the list too (e.g. a legacy id), but still reads fine: untouched.+ listGroups(['unrelated']);+ await flush();+ expect(mocks.getBotGroup.mock.calls.map(([groupId]) => groupId).sort()).toEqual(['gone', 'kept']);+ expect(getBotGroupOutbox('gone')).toEqual([]);+ expect(getBotGroupOutbox('kept')).toHaveLength(1);+ expect(new Set(released().flatMap((ids) => ids.split(',')))).toEqual(new Set(['failed', 'flying']));+ // Its late receipt changes nothing and releases nothing more.+ late.resolve({ ok: true, messageId: 'm1' });+ await flush();+ expect(getBotGroupOutbox('gone')).toEqual([]);+ expect(new Set(released().flatMap((ids) => ids.split(',')))).toEqual(new Set(['failed', 'flying']));+ });++ it('keeps a group that is only missing from the list when the read fails or is not definite', async () => {+ mocks.send.mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' });+ enqueueBotGroupSend(draft({ groupId: 'g1', clientId: 'failed' }, { files: [staged('failed')] }));+ await flush();+ mocks.getBotGroup.mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' });+ listGroups([]);+ await flush();+ mocks.getBotGroup.mockRejectedValueOnce(new Error('offline'));+ listGroups([]);+ await flush();+ expect(getBotGroupOutbox('g1')).toHaveLength(1);+ expect(mocks.cleanupStaged).not.toHaveBeenCalled();+ // Listed groups are never re-read.+ mocks.getBotGroup.mockClear();+ listGroups(['g1']);+ await flush();+ expect(mocks.getBotGroup).not.toHaveBeenCalled();+ });+ });});diff --git a/apps/desktop/src/renderer/features/bots/botGroupOutbox.ts b/apps/desktop/src/renderer/features/bots/botGroupOutbox.tsindex 3bff4fec8c..460d13ef17 100644--- a/apps/desktop/src/renderer/features/bots/botGroupOutbox.ts+++ b/apps/desktop/src/renderer/features/bots/botGroupOutbox.ts@@ -18,7 +18,9 @@* 而服务器副本还没下载好(没有 url / path,或旧版干脆还没出现在列表里)时,按同一 messageId* 把本地预览接到真实消息上,直到副本可用(见 `mergeBotGroupLocalAttachments`)。* - 离开输入框的附件不再受草稿保护:发件箱持有的图片地址(含标注原图与本地预览)登记进存储- * 清理的保护清单,条目移除时同步撤下;删群时回收尚未进入消息的暂存文件。+ * 清理的保护清单,条目移除时同步撤下。尚未进入消息的暂存文件由发件箱回收:群被删除(含+ * 不在当前页的群:列表里消失且读取确认已不存在)时回收该群所有未发出的条目;切换账号时回收+ * 排队中与已失败的条目,在途的那条等它的请求有了结果再定——发出了就不碰,没发出才回收。* - 失败时交还输入框(输入框空着才交还,见 `registerBotGroupComposer`),否则留在时间线上* 显示没发出去,可重试或编辑;失败时输入框不在(切群、分享模式),回来注册输入框时同样交还。* - 切换账号整体清空,旧账号的迟到回执一律丢弃;群被删除时丢弃该群的条目。@@ -39,7 +41,7 @@ import type {import { toBotGroupAttachmentInputs } from './botGroupAttachments';import type { BotGroupTrackedMention } from './botGroupMentions';import { botGroupErrorKey } from './botGroupPresentation';-import { botGroupApi } from './botGroupStore';+import { botGroupApi, getBotGroupListSnapshot, subscribeBotGroups } from './botGroupStore';export type BotGroupOutboxStatus = 'sending' | 'sent' | 'failed';@@ -138,10 +140,20 @@ function emit(): void {for (const listener of listeners) listener();}+/** Staged copies only a message that never reached a message still points at. */+function releaseStaged(files: readonly AttachedFile[]): void {+ if (files.length > 0) cleanupStagedChatAttachmentFiles(files);+}+function ensureOwner(): void {if (isDataOwnerGenerationCurrent(owner)) return;owner = getDataOwnerGeneration();generation += 1;+ // The previous account's failures go with it. Its queued and in-flight sends still hold their+ // files and settle them in `submit`, which knows whether they went out.+ for (const group of groups.values()) {+ for (const entry of group.entries) if (entry.status === 'failed') releaseStaged(entry.files);+ }groups.clear();preparing.clear();protectHeldMedia();@@ -149,6 +161,7 @@ function ensureOwner(): void {function groupOf(groupId: string): GroupOutbox {ensureOwner();+ watchGroupList();let group = groups.get(groupId);if (!group) {group = { entries: EMPTY, chain: Promise.resolve(), claimed: [], latestSequence: 0, previews: NO_PREVIEWS };@@ -254,12 +267,23 @@ export function editBotGroupSend(groupId: string, clientId: string): boolean {function schedule(groupId: string, clientId: string): void {const group = groupOf(groupId);const requestGeneration = generation;- group.chain = group.chain.then(() => submit(groupId, clientId, requestGeneration)).catch(() => undefined);+ // Kept by the request itself: after an account switch the entry is gone but its files are not.+ const files = group.entries.find((entry) => entry.input.clientId === clientId)?.files ?? [];+ group.chain = group.chain.then(() => submit(groupId, clientId, requestGeneration, files)).catch(() => undefined);}-async function submit(groupId: string, clientId: string, requestGeneration: number): Promise<void> {+async function submit(+ groupId: string,+ clientId: string,+ requestGeneration: number,+ files: readonly AttachedFile[],+): Promise<void> {const isCurrent = () => requestGeneration === generation && isDataOwnerGenerationCurrent(owner);- if (!isCurrent()) return;+ // Queued under an account that is gone: it never reached main.+ if (!isCurrent()) {+ releaseStaged(files);+ return;+ }const group = groups.get(groupId);const entry = group?.entries.find((candidate) => candidate.input.clientId === clientId);if (!group || !entry || entry.status !== 'sending') return;@@ -270,11 +294,20 @@ async function submit(groupId: string, clientId: string, requestGeneration: numbif (!api) throw new Error('HOST_NOT_READY');// Drawn annotations are burned in first, as in a task; a failure keeps everything for a retry.const prepared = await prepare(groupId, clientId);+ // The account changed while annotations were burning in: never send it under the new one.+ if (!isCurrent()) {+ releaseStaged(files);+ return;+ }const result: BotGroupSendResult = await api.sendBotGroupMessage({...entry.input,...(prepared.length > 0 ? { attachments: toBotGroupAttachmentInputs(prepared) } : {}),});- if (!isCurrent()) return;+ if (!isCurrent()) {+ // A late answer for the previous account: keep what went out, release what did not.+ if (!result.ok) releaseStaged(files);+ return;+ }if (result.ok) {group.claimed = [...group.claimed, result.messageId].slice(-CLAIMED_LIMIT);update(groupId, clientId, { status: 'sent', messageId: result.messageId, receiptTick: ++tick, baseline: undefined });@@ -285,7 +318,10 @@ async function submit(groupId: string, clientId: string, requestGeneration: numb? 'bots.groupChat.composer.attachmentsFailed': botGroupErrorKey(result.errorCode, 'bots.groupChat.composer.sendFailed');} catch (error) {- if (!isCurrent()) return;+ if (!isCurrent()) {+ releaseStaged(files);+ return;+ }if (isAnnotationBurnInError(error)) errorKey = 'chat.media.annotateBurnFailedNotSent';}const failed = update(groupId, clientId, { status: 'failed', errorKey, baseline: undefined });@@ -399,11 +435,43 @@ export function discardBotGroupOutbox(groupId: string): void {if (!group) return;groups.delete(groupId);for (const entry of group.entries) {- if (entry.status !== 'sent') cleanupStagedChatAttachmentFiles(entry.files);+ if (entry.status !== 'sent') releaseStaged(entry.files);}emit();}+let unwatchGroupList: (() => void) | null = null;+const verifying = new Set<string>();++/**+ * Groups deleted while their page is closed (or from another device) send no event this+ * outbox sees. The group list does: a group that drops out of it is read once more, and only+ * a definite NOT_FOUND discards its outbox (a legacy id still resolves, a failed read keeps it).+ */+function watchGroupList(): void {+ if (unwatchGroupList) return;+ unwatchGroupList = subscribeBotGroups(() => {+ const list = getBotGroupListSnapshot();+ if (!list.loaded) return;+ const listed = new Set(list.groups.map((group) => group.id));+ for (const [groupId, group] of groups) {+ if (listed.has(groupId) || verifying.has(groupId)) continue;+ if (group.entries.length === 0 && group.previews.size === 0) continue;+ const api = botGroupApi();+ if (!api) continue;+ const requestGeneration = generation;+ verifying.add(groupId);+ void api+ .getBotGroup(groupId)+ .then((result) => {+ if (requestGeneration === generation && !result.ok && result.errorCode === 'NOT_FOUND') discardBotGroupOutbox(groupId);+ })+ .catch(() => undefined)+ .finally(() => verifying.delete(groupId));+ }+ });+}+/*** The group's composer is on screen. A message that failed while it was away (another group,* share mode) comes back into it now, the same way as a failure seen in place.@@ -498,5 +566,8 @@ export function resetBotGroupOutboxForTests(): void {owner = getDataOwnerGeneration();groups.clear();preparing.clear();+ verifying.clear();+ unwatchGroupList?.();+ unwatchGroupList = null;composers.clear();}diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.mdindex 56de70f655..2e89632902 100644--- a/docs/product-rules/bot-group-chat.md+++ b/docs/product-rules/bot-group-chat.md@@ -351,7 +351,7 @@ Chris 已明确扩展到多人各带伙伴,并选择「主人按群预先授同一草稿的点名目标 ID、顺序或所有人标记变化,即使显示名字与正文没变,也必须使用新的 `clientId`。只有正文、点名目标、分工标记和附件均不变时,失败重试才复用原发送尝试。-Desktop 主群输入框发送即乐观显示:点发送后消息立即接在时间线末尾,输入框与托盘马上空出,可以接着发下一条;同一个群的提交按发出顺序逐条交给 main,慢于 0.6 秒才在气泡下显示「发送中…」。回执的 `messageId` 是替换依据:时间线读到该消息即换成真实消息,回执之后开始的重读没读到也视为已进历史;推送重读先于回执到达时,只对正在提交的那一条按「基线之后、未被回执认领、正文与附件数一致的自己的消息」做显示去重,最终仍以 `messageId` 为准。附件按输入生成临时列表;带手绘标注的图片入队即烧录,完成后气泡改用烧录后的本地预览,提交与重试复用同一份烧录结果,放回输入框的仍是带笔迹的原件。真实消息到达而服务器副本尚未可用(无 url / path,或旧版尚未列出)时,在同一 `messageId` 内配对:数量一致按发送顺序,旧版逐个列出时按顺序同名(烧录后的名字)配对,继续显示本地预览直到副本可用,不退成缺失、不重复、同名文件不互换。离开输入框的图片(含标注原图与本地预览)登记进存储清理的保护清单直到条目释放;删群时回收尚未进入消息的暂存文件。发送失败绝不自动重发:输入框为空(无文字、附件、分工标签)时把正文、点名、标签与附件原样放回并提示原因,再发沿用原 `clientId`;输入框已有新内容时消息留在时间线上显示「没发出去」,可「重试」(同一 `clientId`)或在输入框清空后「编辑」放回;失败时输入框不在(切到别的群、分享模式),回到该群时同样放回空输入框并提示原因。发件箱原样保存并发出完整发送输入(附件在提交时才烧录标注并序列化),首发与重试不挑字段;除 `clientId` 外的全部字段与附件共同决定能否复用原 `clientId`,新增发送字段无需改动发件箱。发件箱只在 renderer 内存中保留,切群后仍按群隔离,切换账号清空、删群丢弃,不持久化。Thread 回复与手机端仍是等待回执后显示。实现见 `renderer/features/bots/botGroupOutbox.ts`,回归见 `botGroupOutbox.test.ts` 与 `BotGroupChatView.test.tsx`。+Desktop 主群输入框发送即乐观显示:点发送后消息立即接在时间线末尾,输入框与托盘马上空出,可以接着发下一条;同一个群的提交按发出顺序逐条交给 main,慢于 0.6 秒才在气泡下显示「发送中…」。回执的 `messageId` 是替换依据:时间线读到该消息即换成真实消息,回执之后开始的重读没读到也视为已进历史;推送重读先于回执到达时,只对正在提交的那一条按「基线之后、未被回执认领、正文与附件数一致的自己的消息」做显示去重,最终仍以 `messageId` 为准。附件按输入生成临时列表;带手绘标注的图片入队即烧录,完成后气泡改用烧录后的本地预览,提交与重试复用同一份烧录结果,放回输入框的仍是带笔迹的原件。真实消息到达而服务器副本尚未可用(无 url / path,或旧版尚未列出)时,在同一 `messageId` 内配对:数量一致按发送顺序,旧版逐个列出时按顺序同名(烧录后的名字)配对,继续显示本地预览直到副本可用,不退成缺失、不重复、同名文件不互换。离开输入框的图片(含标注原图与本地预览)登记进存储清理的保护清单直到条目释放;尚未进入消息的暂存文件由发件箱回收:群被删除(包括不在当前页、从列表消失且读取确认 `NOT_FOUND` 的群)时回收该群所有未发出的条目;切换账号时回收排队中与已失败的条目,在途的条目按请求结果定——发出的不动,没发出的回收,烧录中途切换账号的不再发出;已发出消息的文件一律不回收。发送失败绝不自动重发:输入框为空(无文字、附件、分工标签)时把正文、点名、标签与附件原样放回并提示原因,再发沿用原 `clientId`;输入框已有新内容时消息留在时间线上显示「没发出去」,可「重试」(同一 `clientId`)或在输入框清空后「编辑」放回;失败时输入框不在(切到别的群、分享模式),回到该群时同样放回空输入框并提示原因。发件箱原样保存并发出完整发送输入(附件在提交时才烧录标注并序列化),首发与重试不挑字段;除 `clientId` 外的全部字段与附件共同决定能否复用原 `clientId`,新增发送字段无需改动发件箱。发件箱只在 renderer 内存中保留,切群后仍按群隔离,切换账号清空、删群丢弃,不持久化。Thread 回复与手机端仍是等待回执后显示。实现见 `renderer/features/bots/botGroupOutbox.ts`,回归见 `botGroupOutbox.test.ts` 与 `BotGroupChatView.test.tsx`。完成全部显式目标校验后,最终点名列表继续沿用排除当前用户自己的既有规则;主群、Thread 与手机直连均一致,不因显式列表或所有人标记改变。