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(desktop): 群聊发件箱保留标注预览与附件归属,失败消息回到输入框

Dash6fe9d4a0b284
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx b/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx
index 3753e676a7..17e2fac28b 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx
@@ -236,7 +236,12 @@ export function BotGroupComposer({
// A message that did not go out comes back only into an empty input: never over new
// text, a new tag or files added meanwhile. Pressing send again reuses its clientId.
- const restoreAttachments = attachmentState.restoreFiles;
+ // Registered once per group (mount / group change): re-registering on every render would
+ // pull a failed message back in the moment the user clears the input.
+ const restoreAttachmentsRef = useRef(attachmentState.restoreFiles);
+ restoreAttachmentsRef.current = attachmentState.restoreFiles;
+ const tRef = useRef(t);
+ tRef.current = t;
useEffect(
() =>
registerBotGroupComposer(groupId, {
@@ -249,12 +254,12 @@ export function BotGroupComposer({
const restoredDivision = entry.input.division === true;
divisionRef.current = restoredDivision;
if (restoredDivision) setDivision(true);
- if (entry.files.length > 0) attachmentsRef.current = restoreAttachments(entry.files);
+ if (entry.files.length > 0) attachmentsRef.current = restoreAttachmentsRef.current(entry.files);
return true;
},
- notifyFailed: (errorKey) => toast.error(t(errorKey)),
+ notifyFailed: (errorKey) => toast.error(tRef.current(errorKey)),
}),
- [groupId, restoreAttachments, t],
+ [groupId],
);
const send = () => {
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
index 848fddc1c0..7dbbeae86f 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
@@ -1344,6 +1344,44 @@ describe('BotGroupChatView', () => {
expect(screen.getAllByAltText('photo.png')).toHaveLength(1);
});
+ it('puts a message that failed while the group was closed back into its empty composer on return', async () => {
+ const send = pendingSend();
+ const view = renderView();
+ const tree = () => (
+ <Tooltip.Provider>
+ <FeatureSidebarSlotProvider isCollapsed={false}>
+ <HeaderSlot />
+ <BotGroupChatView />
+ </FeatureSidebarSlotProvider>
+ </Tooltip.Provider>
+ );
+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;
+ fireEvent.change(input, { target: { value: '离开时失败的' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(1));
+ mocks.groupId = 'g2';
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ id: 'g2', name: '另一个群' }) });
+ view.rerender(tree());
+ await screen.findByText('另一个群');
+ await send.resolve({ ok: false, errorCode: 'INTERNAL', message: '' });
+ // Nothing of g1 shows here, and g2's composer is not touched.
+ expect(outboxItems()).toHaveLength(0);
+ expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe('');
+
+ mocks.groupId = 'g1';
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail() });
+ view.rerender(tree());
+ await screen.findByText('周六 8:10 有票');
+ await waitFor(() => expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe('离开时失败的'));
+ expect(outboxItems()).toHaveLength(0);
+ expect(mocks.toastError).toHaveBeenCalledWith('bots.groupChat.composer.sendFailed');
+ // Sending it again is the same attempt.
+ mocks.sendBotGroupMessage.mockResolvedValueOnce({ ok: true, messageId: 'u2' });
+ fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter' });
+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(2));
+ expect(mocks.sendBotGroupMessage.mock.calls[1]![0].clientId).toBe(mocks.sendBotGroupMessage.mock.calls[0]![0].clientId);
+ });
+
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.ts
index b0335c9444..4bac65e98b 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botGroupOutbox.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botGroupOutbox.test.ts
@@ -29,6 +29,9 @@ import {
const mocks = vi.hoisted(() => ({
owner: 1,
send: vi.fn<(input: BotGroupSendInput) => Promise<BotGroupSendResult>>(),
+ materialize: vi.fn(async (files: readonly AttachedFile[]) => [...files]),
+ protectedUrls: [] as string[],
+ cleanupStaged: vi.fn(),
}));
vi.mock('@/contexts/dataOwnerGeneration', () => ({
@@ -40,7 +43,15 @@ vi.mock('../botGroupStore', () => ({
}));
vi.mock('@/lib/annotationBurnIn', () => ({
isAnnotationBurnInError: () => false,
- materializeAnnotatedAttachmentsForSend: async (files: readonly AttachedFile[]) => [...files],
+ materializeAnnotatedAttachmentsForSend: (files: readonly AttachedFile[]) => mocks.materialize(files),
+}));
+vi.mock('@/lib/composerDraftStore', () => ({
+ setBotGroupOutboxAttachmentUrls: (urls: readonly string[]) => {
+ mocks.protectedUrls = [...new Set(urls)].sort();
+ },
+}));
+vi.mock('@/lib/chatAttachmentStageCleanup', () => ({
+ cleanupStagedChatAttachmentFiles: (files: unknown) => mocks.cleanupStaged(files),
}));
/** A send main has not answered yet; the test decides when and how. */
@@ -115,6 +126,9 @@ function project(groupId: string, messages: BotGroupMessageView[]) {
beforeEach(() => {
mocks.owner = 1;
mocks.send.mockReset();
+ mocks.materialize.mockReset().mockImplementation(async (files: readonly AttachedFile[]) => [...files]);
+ mocks.protectedUrls = [];
+ mocks.cleanupStaged.mockReset();
resetBotGroupOutboxForTests();
});
@@ -365,7 +379,8 @@ describe('botGroupOutbox', () => {
it('keeps each local preview until its server copy is usable, under the server id, in send order', () => {
const mine = [local('l1', 'a.png'), local('l2', 'b.png')];
- expect(mergeBotGroupLocalAttachments([placeholder('s2', 'b.png'), placeholder('s1', 'a.png')], mine)).toEqual([
+ // The server keeps the order the files were sent in.
+ expect(mergeBotGroupLocalAttachments([placeholder('s1', 'a.png'), placeholder('s2', 'b.png')], mine)).toEqual([
{ ...mine[0], id: 's1' },
{ ...mine[1], id: 's2' },
]);
@@ -414,5 +429,127 @@ describe('botGroupOutbox', () => {
expect(projected.pending).toEqual([]);
expect(projected.localAttachments.get('m1')).toEqual(getBotGroupOutbox('g1')[0]!.attachments);
});
+
+ it('never swaps two files with the same name, whether the server lists all of them or not yet', () => {
+ // Two different photo.png; the first was drawn on, so its burned-in copy is renamed.
+ const mine = [local('l1', 'photo-annotated.png'), local('l2', 'photo.png')];
+ expect(mergeBotGroupLocalAttachments(
+ [placeholder('s1', 'photo-annotated.png'), usable('s2', 'photo.png')], mine,
+ )).toEqual([{ ...mine[0], id: 's1' }, usable('s2', 'photo.png')]);
+ // Copies listed one by one as they download (older servers).
+ expect(mergeBotGroupLocalAttachments([usable('s2', 'photo.png')], mine)).toEqual([mine[0], usable('s2', 'photo.png')]);
+ expect(mergeBotGroupLocalAttachments([usable('s1', 'photo-annotated.png')], mine)).toEqual([
+ usable('s1', 'photo-annotated.png'), mine[1],
+ ]);
+ });
+ });
+
+ describe('drawn annotations', () => {
+ const original = {
+ id: 'l1', name: 'photo.png', path: '/tmp/photo.png', size: 1, category: 'image', mimeType: 'image/png', type: 'image',
+ url: 'cindy-media://blobs/original.png', annotationStrokes: [{ points: [{ x: 1, y: 1 }] }],
+ } as unknown as AttachedFile;
+ const burned = {
+ ...original, name: 'photo-annotated.png', url: 'cindy-media://blobs/burned.png', annotated: true,
+ annotationSourceUrl: 'cindy-media://blobs/original.png',
+ } as unknown as AttachedFile;
+
+ it('shows the burned-in copy as soon as it is ready and burns once for every (re)try', async () => {
+ let finishBurn!: (files: AttachedFile[]) => void;
+ mocks.materialize.mockImplementationOnce(() => new Promise((resolve) => { finishBurn = resolve; }));
+ mocks.send.mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' })
+ .mockResolvedValueOnce({ ok: true, messageId: 'm1' });
+ enqueueBotGroupSend(draft({ text: '圈出来的地方' }, { files: [original] }));
+ await flush();
+ expect(mocks.send).not.toHaveBeenCalled();
+ finishBurn([burned]);
+ await flush();
+ expect(getBotGroupOutbox('g1')[0]!.attachments).toEqual([
+ expect.objectContaining({ name: 'photo-annotated.png', url: 'cindy-media://blobs/burned.png' }),
+ ]);
+ retryBotGroupSend('g1', 'c1');
+ await flush();
+ expect(mocks.materialize).toHaveBeenCalledTimes(1);
+ expect(mocks.send.mock.calls.map(([input]) => input.attachments?.[0]?.url)).toEqual([
+ 'cindy-media://blobs/burned.png', 'cindy-media://blobs/burned.png',
+ ]);
+ });
+
+ it('hands the original with its strokes back to the composer, not the burned copy', async () => {
+ const restore = vi.fn(() => true);
+ registerBotGroupComposer('g1', { restore, notifyFailed: vi.fn() });
+ mocks.materialize.mockResolvedValueOnce([burned]);
+ mocks.send.mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' });
+ enqueueBotGroupSend(draft({}, { files: [original] }));
+ await flush();
+ expect(restore).toHaveBeenCalledWith(expect.objectContaining({ files: [original] }));
+ });
+
+ it('tries the burn again on 重试 after it failed', async () => {
+ mocks.materialize.mockRejectedValueOnce(new Error('burn')).mockResolvedValueOnce([burned]);
+ mocks.send.mockResolvedValueOnce({ ok: true, messageId: 'm1' });
+ enqueueBotGroupSend(draft({}, { files: [original] }));
+ await flush();
+ expect(getBotGroupOutbox('g1')[0]!.status).toBe('failed');
+ expect(mocks.send).not.toHaveBeenCalled();
+ retryBotGroupSend('g1', 'c1');
+ await flush();
+ expect(mocks.materialize).toHaveBeenCalledTimes(2);
+ expect(mocks.send.mock.calls[0]![0].attachments?.[0]?.url).toBe('cindy-media://blobs/burned.png');
+ });
+ });
+
+ describe('holding files outside the draft', () => {
+ const file = {
+ id: 'f1', name: 'shot.png', path: '/staged/shot.bin', size: 1, category: 'image', mimeType: 'image/png', type: 'image',
+ url: 'cindy-media://blobs/shot.png',
+ } as unknown as AttachedFile;
+
+ it('protects the media of messages still held from storage cleanup until they are settled', async () => {
+ const pending = deferred();
+ mocks.send.mockReturnValueOnce(pending.promise);
+ enqueueBotGroupSend(draft({ text: '' }, { files: [file] }));
+ await flush();
+ expect(mocks.protectedUrls).toEqual(['cindy-media://blobs/shot.png']);
+ pending.resolve({ ok: true, messageId: 'm1' });
+ await flush();
+ expect(mocks.protectedUrls).toEqual(['cindy-media://blobs/shot.png']);
+ noteBotGroupTimeline('g1', [msg({ id: 'm1', sequence: 1, attachments: [
+ { id: 's1', name: 'shot.png', category: 'image', mimeType: 'image/png', size: 1, url: 'cindy-media://blobs/server.png', path: null },
+ ] })], beginBotGroupTimelineRead());
+ expect(mocks.protectedUrls).toEqual([]);
+ });
+
+ it('cleans up staged copies of unsent messages when the group is deleted, never of sent ones', async () => {
+ mocks.send.mockResolvedValueOnce({ ok: true, messageId: 'm1' })
+ .mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' });
+ const sentFile = { ...file, id: 'f0', path: '/staged/sent.bin' } as AttachedFile;
+ enqueueBotGroupSend(draft({ clientId: 'sent' }, { files: [sentFile] }));
+ enqueueBotGroupSend(draft({ clientId: 'unsent' }, { files: [file] }));
+ await flush();
+ discardBotGroupOutbox('g1');
+ expect(mocks.cleanupStaged).toHaveBeenCalledTimes(1);
+ expect(mocks.cleanupStaged).toHaveBeenCalledWith([file]);
+ expect(mocks.protectedUrls).toEqual([]);
+ });
+ });
+
+ describe('a failure while the composer was away', () => {
+ it('comes back into an empty composer when it registers, with the reason', async () => {
+ mocks.send.mockResolvedValueOnce({ ok: false, errorCode: 'MENTION_UNAVAILABLE', message: '' });
+ enqueueBotGroupSend(draft());
+ await flush();
+ expect(getBotGroupOutbox('g1').map((entry) => entry.status)).toEqual(['failed']);
+ const busy = { restore: vi.fn(() => false), notifyFailed: vi.fn() };
+ const release = registerBotGroupComposer('g1', busy);
+ expect(busy.notifyFailed).not.toHaveBeenCalled();
+ expect(getBotGroupOutbox('g1')).toHaveLength(1);
+ release();
+ const empty = { restore: vi.fn(() => true), notifyFailed: vi.fn() };
+ registerBotGroupComposer('g1', empty);
+ expect(empty.restore).toHaveBeenCalledWith(expect.objectContaining({ input: expect.objectContaining({ clientId: 'c1' }) }));
+ expect(empty.notifyFailed).toHaveBeenCalledWith('bots.groupChat.errors.mentionUnavailable');
+ expect(getBotGroupOutbox('g1')).toEqual([]);
+ });
});
});
diff --git a/apps/desktop/src/renderer/features/bots/botGroupOutbox.ts b/apps/desktop/src/renderer/features/bots/botGroupOutbox.ts
index 53665388bf..3bff4fec8c 100644
--- a/apps/desktop/src/renderer/features/bots/botGroupOutbox.ts
+++ b/apps/desktop/src/renderer/features/bots/botGroupOutbox.ts
@@ -3,7 +3,7 @@
*
* 只是 renderer 内存里的展示状态,不持久化,也不替代 main 的幂等与服务器的权威时间线:
* - 每条消息保存 composer 交来的完整发送输入(`BotGroupSendInput`,附件除外——附件在
- * 提交时才烧录标注并序列化),提交与重试都原样发出,这里不挑字段;新增发送字段只需
+ * 入队时就开始烧录标注,提交时序列化),提交与重试都原样发出,这里不挑字段;新增发送字段只需
* composer 放进 `input`,显示、回执与重试自动带上。
* - `input.clientId` 是身份,失败重试沿用同一个 clientId,main 与服务器据此去重,
* 所以这里绝不自动重发。
@@ -13,17 +13,22 @@
* - 推送重读可能先于回执到达。此时只对正在提交的那一条(同群同时最多一条)做显示上的
* 去重:基线之后出现、未被任何回执认领、正文与附件数一致的自己的消息视为它,回执到达后
* 仍以 messageId 为准。
- * - 附件:临时消息从输入的附件生成列表。真实消息到了而服务器副本还没下载好(没有 url / path,
- * 或旧版干脆还没出现在列表里)时,按同一 messageId 把本地预览接到真实消息上,直到副本可用,
- * 不让已看见的图片先退成缺失再出现(见 `mergeBotGroupLocalAttachments`)。
+ * - 附件:临时消息从输入的附件生成列表;带手绘标注的图片烧录完成后改用烧录后的本地预览
+ * (同一份烧录结果也用于提交与重试,不重复烧录;放回输入框的仍是带笔迹的原件)。真实消息到了
+ * 而服务器副本还没下载好(没有 url / path,或旧版干脆还没出现在列表里)时,按同一 messageId
+ * 把本地预览接到真实消息上,直到副本可用(见 `mergeBotGroupLocalAttachments`)。
+ * - 离开输入框的附件不再受草稿保护:发件箱持有的图片地址(含标注原图与本地预览)登记进存储
+ * 清理的保护清单,条目移除时同步撤下;删群时回收尚未进入消息的暂存文件。
* - 失败时交还输入框(输入框空着才交还,见 `registerBotGroupComposer`),否则留在时间线上
- * 显示没发出去,可重试或编辑。
+ * 显示没发出去,可重试或编辑;失败时输入框不在(切群、分享模式),回来注册输入框时同样交还。
* - 切换账号整体清空,旧账号的迟到回执一律丢弃;群被删除时丢弃该群的条目。
*/
import { useCallback, useSyncExternalStore } from 'react';
import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
import { isAnnotationBurnInError, materializeAnnotatedAttachmentsForSend } from '@/lib/annotationBurnIn';
+import { cleanupStagedChatAttachmentFiles } from '@/lib/chatAttachmentStageCleanup';
+import { setBotGroupOutboxAttachmentUrls } from '@/lib/composerDraftStore';
import type { AttachedFile } from '@/lib/fileTypes';
import type {
BotGroupAttachment,
@@ -38,7 +43,7 @@ import { botGroupApi } from './botGroupStore';
export type BotGroupOutboxStatus = 'sending' | 'sent' | 'failed';
-/** The send as main receives it; attachments are prepared from `files` at submission. */
+/** The send as main receives it; attachments are prepared from `files` (see `prepared`). */
export type BotGroupOutboxSendInput = Omit<BotGroupSendInput, 'attachments'>;
/** What the composer hands over when the user presses send. */
@@ -67,8 +72,10 @@ export function botGroupSendSignature(input: BotGroupOutboxSendInput, attachment
export interface BotGroupOutboxEntry extends BotGroupOutboxDraft {
status: BotGroupOutboxStatus;
createdAt: number;
- /** The attachments as the timeline shows them. */
+ /** The attachments as the timeline shows them (the burned-in copies once `prepared`). */
attachments: readonly BotGroupAttachment[];
+ /** `files` with drawn annotations burned in; reused by every (re)try. */
+ prepared?: readonly AttachedFile[];
/** From the receipt. */
messageId?: string;
/** Order of the receipt against timeline reads (see `beginBotGroupTimelineRead`). */
@@ -106,8 +113,28 @@ let tick = 0;
const groups = new Map<string, GroupOutbox>();
const composers = new Map<string, BotGroupComposerHandle>();
const listeners = new Set<() => void>();
+/** One burn-in per message, shared by the bubble and its submission. */
+const preparing = new Map<string, Promise<readonly AttachedFile[]>>();
+
+/** Media only this outbox still refers to; storage cleanup must not sweep it. */
+function protectHeldMedia(): void {
+ const urls: string[] = [];
+ const add = (file: { url?: string | null; annotationSourceUrl?: string }) => {
+ if (file.url) urls.push(file.url);
+ if (file.annotationSourceUrl) urls.push(file.annotationSourceUrl);
+ };
+ for (const group of groups.values()) {
+ for (const entry of group.entries) {
+ entry.files.forEach(add);
+ entry.prepared?.forEach(add);
+ }
+ for (const preview of group.previews.values()) preview.forEach(add);
+ }
+ setBotGroupOutboxAttachmentUrls(urls);
+}
function emit(): void {
+ protectHeldMedia();
for (const listener of listeners) listener();
}
@@ -116,6 +143,8 @@ function ensureOwner(): void {
owner = getDataOwnerGeneration();
generation += 1;
groups.clear();
+ preparing.clear();
+ protectHeldMedia();
}
function groupOf(groupId: string): GroupOutbox {
@@ -174,6 +203,33 @@ export function enqueueBotGroupSend(draft: BotGroupOutboxDraft): void {
group.entries = [...group.entries.filter((existing) => existing.input.clientId !== clientId), entry];
emit();
schedule(groupId, clientId);
+ // Burn annotations in now, not when the message's turn comes: the bubble shows the result.
+ if (entry.files.length > 0) void prepare(groupId, clientId).catch(() => undefined);
+}
+
+/** The message's files with annotations burned in, once; a failure is retried by the next call. */
+function prepare(groupId: string, clientId: string): Promise<readonly AttachedFile[]> {
+ const entry = groups.get(groupId)?.entries.find((candidate) => candidate.input.clientId === clientId);
+ if (!entry) return Promise.reject(new Error('OUTBOX_ENTRY_GONE'));
+ if (entry.prepared) return Promise.resolve(entry.prepared);
+ if (entry.files.length === 0) return Promise.resolve([]);
+ const key = `${groupId}\n${clientId}`;
+ const existing = preparing.get(key);
+ if (existing) return existing;
+ const requestGeneration = generation;
+ const pending = materializeAnnotatedAttachmentsForSend(entry.files, entry.attachmentScope, { burnFailure: 'abort' })
+ .then((files) => {
+ const prepared = files ?? [];
+ if (requestGeneration === generation) {
+ update(groupId, clientId, { prepared, attachments: displayAttachments(prepared) });
+ }
+ return prepared;
+ })
+ .finally(() => {
+ if (preparing.get(key) === pending) preparing.delete(key);
+ });
+ preparing.set(key, pending);
+ return pending;
}
/** 重试 on a message that did not go out: the same clientId, so main returns any copy it already has. */
@@ -213,10 +269,7 @@ async function submit(groupId: string, clientId: string, requestGeneration: numb
try {
if (!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 =
- entry.files.length > 0
- ? ((await materializeAnnotatedAttachmentsForSend(entry.files, entry.attachmentScope, { burnFailure: 'abort' })) ?? [])
- : [];
+ const prepared = await prepare(groupId, clientId);
const result: BotGroupSendResult = await api.sendBotGroupMessage({
...entry.input,
...(prepared.length > 0 ? { attachments: toBotGroupAttachmentInputs(prepared) } : {}),
@@ -286,27 +339,26 @@ function isUsable(attachment: BotGroupAttachment): boolean {
}
/**
- * Pair the server's attachments of a message with the local ones it was sent with: by name
- * first, then in order when the remaining counts agree (a burned-in image can be renamed).
+ * Pair the server's attachments of a message with the local ones it was sent with. The server
+ * keeps the order they were sent in, so equal counts pair by position. An older server lists a
+ * copy only once it is downloaded; then pair by name in that same order, so two files with the
+ * same name never swap. Local names are the burned-in ones (see `prepared`), as on the server.
* Returns, for each local attachment, the server copy it matches (or undefined), plus the
* server attachments nothing local matched.
*/
function pairLocalAttachments(server: readonly BotGroupAttachment[], local: readonly BotGroupAttachment[]) {
+ if (server.length === local.length) return { pairs: [...server], extra: [] as BotGroupAttachment[] };
const used = new Set<number>();
+ let next = 0;
const pairs: Array<BotGroupAttachment | undefined> = local.map((file) => {
- const index = server.findIndex((candidate, at) => !used.has(at) && candidate.name === file.name);
- if (index < 0) return undefined;
- used.add(index);
- return server[index];
+ for (let at = next; at < server.length; at += 1) {
+ if (server[at]!.name !== file.name) continue;
+ used.add(at);
+ next = at + 1;
+ return server[at];
+ }
+ return undefined;
});
- const rest = server.flatMap((candidate, at) => (used.has(at) ? [] : [at]));
- const unpaired = pairs.flatMap((pair, at) => (pair ? [] : [at]));
- if (rest.length === unpaired.length) {
- unpaired.forEach((at, order) => {
- used.add(rest[order]!);
- pairs[at] = server[rest[order]!];
- });
- }
return { pairs, extra: server.filter((_, at) => !used.has(at)) };
}
@@ -337,15 +389,32 @@ function botGroupLocalAttachmentsSettled(
return pairLocalAttachments(server, local).pairs.every((echo) => echo !== undefined && isUsable(echo));
}
-/** The group was deleted: nothing of it is left to send or show. */
+/**
+ * The group was deleted: nothing of it is left to send or show. Staged copies of files that
+ * never reached a message go too; the draft no longer lists them, so nothing else would.
+ */
export function discardBotGroupOutbox(groupId: string): void {
ensureOwner();
- if (!groups.delete(groupId)) return;
+ const group = groups.get(groupId);
+ if (!group) return;
+ groups.delete(groupId);
+ for (const entry of group.entries) {
+ if (entry.status !== 'sent') cleanupStagedChatAttachmentFiles(entry.files);
+ }
emit();
}
+/**
+ * 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.
+ */
export function registerBotGroupComposer(groupId: string, handle: BotGroupComposerHandle): () => void {
composers.set(groupId, handle);
+ const failed = groups.get(groupId)?.entries.find((entry) => entry.status === 'failed');
+ if (failed && handle.restore(failed)) {
+ remove(groupId, failed.input.clientId);
+ handle.notifyFailed(failed.errorKey ?? 'bots.groupChat.composer.sendFailed');
+ }
return () => {
if (composers.get(groupId) === handle) composers.delete(groupId);
};
@@ -428,5 +497,6 @@ export function resetBotGroupOutboxForTests(): void {
generation += 1;
owner = getDataOwnerGeneration();
groups.clear();
+ preparing.clear();
composers.clear();
}
diff --git a/apps/desktop/src/renderer/lib/composerDraftStore.ts b/apps/desktop/src/renderer/lib/composerDraftStore.ts
index 680cbe2cdd..c901860454 100644
--- a/apps/desktop/src/renderer/lib/composerDraftStore.ts
+++ b/apps/desktop/src/renderer/lib/composerDraftStore.ts
@@ -216,6 +216,7 @@ const remoteOptimisticRecoveryBatchSnapshots = new WeakMap<
Map<string, RemoteOptimisticDraftSnapshot>
>();
let remoteOptimisticAttachmentUrls: string[] = [];
+let botGroupOutboxAttachmentUrls: string[] = [];
let activeDataOwnerId: string | null = null;
/**
@@ -723,7 +724,7 @@ export function restoreRemoteOptimisticDraft(
* 没关系,main 侧只抽 cindy-media 指纹)。
*/
export function getAllDraftAttachmentUrls(): string[] {
- const urls = new Set<string>(remoteOptimisticAttachmentUrls);
+ const urls = new Set<string>([...remoteOptimisticAttachmentUrls, ...botGroupOutboxAttachmentUrls]);
// Owner switches retain each owner's draft so switching back can restore it.
// Protect every retained namespace as well; reporting only the active owner
// would leave an old owner's still-restorable attachment eligible for sweep.
@@ -755,6 +756,23 @@ export function setRemoteOptimisticAttachmentUrls(urls: readonly string[]): void
syncDraftUrlsToMain();
}
+/**
+ * Keep media held by group chat messages that left the composer but are still being
+ * sent or kept for 重试 live (botGroupOutbox.ts). A separate slot: the task outbox above
+ * replaces its own list wholesale.
+ */
+export function setBotGroupOutboxAttachmentUrls(urls: readonly string[]): void {
+ const next = [...new Set(urls)].sort();
+ if (
+ next.length === botGroupOutboxAttachmentUrls.length &&
+ next.every((url, index) => url === botGroupOutboxAttachmentUrls[index])
+ ) {
+ return;
+ }
+ botGroupOutboxAttachmentUrls = next;
+ syncDraftUrlsToMain();
+}
+
/**
* 草稿附件集合变化时把全量 URL 推给 main 登记(多窗口防误删:每个窗口是
* 独立 renderer 进程、各一份本 Map,别的窗口发起清理时只能靠 main 侧登记表
diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.md
index 5cb017d28e..56de70f655 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` 内配对:数量一致按发送顺序,旧版逐个列出时按顺序同名(烧录后的名字)配对,继续显示本地预览直到副本可用,不退成缺失、不重复、同名文件不互换。离开输入框的图片(含标注原图与本地预览)登记进存储清理的保护清单直到条目释放;删群时回收尚未进入消息的暂存文件。发送失败绝不自动重发:输入框为空(无文字、附件、分工标签)时把正文、点名、标签与附件原样放回并提示原因,再发沿用原 `clientId`;输入框已有新内容时消息留在时间线上显示「没发出去」,可「重试」(同一 `clientId`)或在输入框清空后「编辑」放回;失败时输入框不在(切到别的群、分享模式),回到该群时同样放回空输入框并提示原因。发件箱原样保存并发出完整发送输入(附件在提交时才烧录标注并序列化),首发与重试不挑字段;除 `clientId` 外的全部字段与附件共同决定能否复用原 `clientId`,新增发送字段无需改动发件箱。发件箱只在 renderer 内存中保留,切群后仍按群隔离,切换账号清空、删群丢弃,不持久化。Thread 回复与手机端仍是等待回执后显示。实现见 `renderer/features/bots/botGroupOutbox.ts`,回归见 `botGroupOutbox.test.ts` 与 `BotGroupChatView.test.tsx`。
完成全部显式目标校验后,最终点名列表继续沿用排除当前用户自己的既有规则;主群、Thread 与手机直连均一致,不因显式列表或所有人标记改变。