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(chat): retain direct receipts and release definitively refused sends

Chrisf3eacc268e7c
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 741515d483..6827f767ce 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botGroupOutbox.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botGroupOutbox.test.ts
@@ -952,7 +952,7 @@ describe('botGroupOutbox', () => {
// Unit regression: a restart between local enqueue and the HTTP response used to lose
// ownership. The production outbox must save first, then restore the same clientId FIFO.
-it('durably restores a failed send and the next queued message, settling only actual receipts', async () => {
+it.each(['group', 'direct'] as const)('durably restores %s sends and reconciles both receipt pages without deleting pending entries', async kind => {
vi.useFakeTimers();
const saved = new Map<string, unknown>();
mocks.storage = async request => {
@@ -961,14 +961,16 @@ it('durably restores a failed send and the next queued message, settling only ac
return request.action === 'list' ? [...saved.values()] : [];
};
mocks.send.mockRejectedValueOnce(new Error('offline'));
- await enqueueBotGroupSend(draft({ clientId: 'first' }));
- await enqueueBotGroupSend(draft({ clientId: 'second' }));
+ const conversation = kind === 'direct' ? { conversationKind: 'direct' as const } : {};
+ await enqueueBotGroupSend(draft({ clientId: 'first', ...conversation }));
+ await enqueueBotGroupSend(draft({ clientId: 'second', ...conversation }));
await vi.advanceTimersByTimeAsync(0);
expect(mocks.send).toHaveBeenCalledTimes(1);
expect(saved.size).toBe(2);
resetBotGroupOutboxForTests();
mocks.send.mockImplementation(async input => ({ ok: true, messageId: `server-${input.clientId}` }));
- mocks.getBotGroup.mockResolvedValue({ ok: true, group: { messages: [] } });
+ mocks.getBotGroup.mockImplementation(async (_id, options) => kind === 'direct' && options?.conversationKind !== 'direct'
+ ? { ok: false, errorCode: 'NOT_FOUND' } : { ok: true, group: { messages: [] } });
const events = new EventTarget();
vi.stubGlobal('window', events);
const stop = startBotGroupOutbox();
@@ -976,13 +978,19 @@ it('durably restores a failed send and the next queued message, settling only ac
await vi.advanceTimersByTimeAsync(10_000);
expect(mocks.send.mock.calls.map(([input]) => input.clientId)).toEqual(['first', 'first', 'second']);
expect(getBotGroupOutbox('g1').map(row => row.status)).toEqual(['sent', 'sent']);
+ // Direct chats need not appear in the group list. Its absence must use the
+ // same direct read contract rather than erase valid receipts as NOT_FOUND.
+ listGroups([]);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(getBotGroupOutbox('g1')).toHaveLength(2);
noteBotGroupTimeline('g1', [msg({ id: 'unrelated', sequence: 20 })], beginBotGroupTimelineRead());
expect(saved.size).toBe(2);
- mocks.getBotGroup.mockImplementation(async (_id, options) => ({ ok: true, group: options?.beforeSequence
+ mocks.getBotGroup.mockImplementation(async (_id, options) => kind === 'direct' && options?.conversationKind !== 'direct'
+ ? { ok: false, errorCode: 'NOT_FOUND' } : ({ ok: true, group: options?.beforeSequence
? { messages: [msg({ id: 'server-first', sequence: 1 }), msg({ id: 'server-second', sequence: 2 })], hasMoreBefore: false }
: { messages: [msg({ id: 'newer', sequence: 20 })], hasMoreBefore: true } }));
await vi.advanceTimersByTimeAsync(5_000);
- expect(mocks.getBotGroup).toHaveBeenCalledWith('g1', { beforeSequence: 20 });
+ expect(mocks.getBotGroup).toHaveBeenCalledWith('g1', { beforeSequence: 20, ...conversation });
expect(saved.size).toBe(0);
} finally { stop(); vi.unstubAllGlobals(); vi.useRealTimers(); }
});
diff --git a/apps/desktop/src/renderer/features/bots/botGroupOutbox.ts b/apps/desktop/src/renderer/features/bots/botGroupOutbox.ts
index 89e84f3a40..6156f2ca06 100644
--- a/apps/desktop/src/renderer/features/bots/botGroupOutbox.ts
+++ b/apps/desktop/src/renderer/features/bots/botGroupOutbox.ts
@@ -196,7 +196,9 @@ export function startBotGroupOutbox(): () => void {
}
if (group.entries.some(entry => entry.status === 'sent')) {
const token = beginBotGroupTimelineRead();
- let result = await botGroupApi()!.getBotGroup(groupId);
+ const options = group.entries.some(entry => entry.input.conversationKind === 'direct')
+ ? { conversationKind: 'direct' as const } : undefined;
+ let result = options ? await botGroupApi()!.getBotGroup(groupId, options) : await botGroupApi()!.getBotGroup(groupId);
if (!current()) return;
if (result.ok) {
noteBotGroupTimeline(groupId, result.group.messages, token);
@@ -205,7 +207,7 @@ export function startBotGroupOutbox(): () => void {
while (result.ok && result.group.hasMoreBefore && group.entries.some(entry => entry.status === 'sent')) {
const before = Math.min(...result.group.messages.map(message => message.sequence));
if (!Number.isFinite(before)) break;
- result = await botGroupApi()!.getBotGroup(groupId, { beforeSequence: before });
+ result = await botGroupApi()!.getBotGroup(groupId, { ...options, beforeSequence: before });
if (!current()) return;
if (!result.ok) break;
noteBotGroupTimeline(groupId, result.group.messages, token);
@@ -610,8 +612,9 @@ function verifyGroupGone(groupId: string, attempt: number): void {
const requestOwner = getDataOwnerGeneration();
let definite = false;
verifying.add(groupId);
- void api
- .getBotGroup(groupId)
+ const options = group.entries.some(entry => entry.input.conversationKind === 'direct')
+ ? { conversationKind: 'direct' as const } : undefined;
+ void (options ? api.getBotGroup(groupId, options) : api.getBotGroup(groupId))
.then((result) => {
if (!isDataOwnerGenerationCurrent(requestOwner)) return;
definite = result.ok || result.errorCode === 'NOT_FOUND';
diff --git a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx
index 15074bb879..8c02223e1d 100644
--- a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx
+++ b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx
@@ -645,3 +645,52 @@ it('persists the exact uncertain send across restart and never rebuilds its reci
expect(store.getSnapshot()[0]).toMatchObject({ state: 'confirming', chat: { messageId: self } });
await store.activate('other-account'); expect(store.getSnapshot()).toEqual([]);
});
+
+// Review regression (integration): a definitive first-POST rejection is safe to cancel,
+// but a rejection after an unknown earlier outcome cannot revoke its dedup identity.
+it.each([400, 403])('can cancel a definitely refused %s send after reload and unblock the next message', async status => {
+ showChat = true; await render();
+ const original = h.auth.apiFetch.getMockImplementation()!;
+ h.auth.apiFetch.mockImplementation(async (path, options) => {
+ if (path.endsWith('/messages') && options?.method === 'POST') throw Object.assign(new Error('Rejected'), { status });
+ return original(path, options);
+ });
+ await act(async () => { await send({ text: 'rejected', clientId: 'rejected-first', mentions: { all: false, botIds: [] } }); });
+ expect(mobileDurableOutbox.getSnapshot()[0]).toMatchObject({ state: 'failed', enqueueStarted: false });
+ // Reauthorize/reopen the same group; do not silently send the suspended draft.
+ h.auth.apiFetch.mockImplementation(original);
+ await act(async () => { chat.reload(); });
+ const account = getMobileAuthOwner().accountKey;
+ await act(async () => { await mobileDurableOutbox.activate(''); await mobileDurableOutbox.activate(account); });
+ await act(async () => { await chat.pendingAction!('rejected-first', 'cancel'); });
+ expect(mobileDurableOutbox.getSnapshot()).toEqual([]);
+ await act(async () => { await send({ text: 'next', clientId: 'after-cancel', mentions: { all: false, botIds: [] } }); });
+ expect(h.auth.apiFetch.mock.calls.filter(([path, options]) => path.endsWith('/messages') && options?.method === 'POST'
+ && options.body.operationId === 'after-cancel')).toHaveLength(1);
+ expect(mobileDurableOutbox.getSnapshot().some(row => row.item.clientId === 'rejected-first')).toBe(false);
+});
+
+it('keeps an uncertain send frozen and uncancellable when a later attempt is rejected', async () => {
+ showChat = true; await render();
+ const original = h.auth.apiFetch.getMockImplementation()!;
+ let attempt = 0;
+ const posted: unknown[] = [];
+ h.auth.apiFetch.mockImplementation(async (path, options) => {
+ if (path.endsWith('/messages') && options?.method === 'POST') {
+ posted.push(options.body); attempt++;
+ if (attempt === 1) throw new Error('response lost');
+ throw Object.assign(new Error('Rejected later'), { status: 400 });
+ }
+ return original(path, options);
+ });
+ await act(async () => { await send({ text: 'uncertain', clientId: 'uncertain-first', mentions: { all: false, botIds: [] } }); });
+ await act(async () => {
+ await expect(chat.pendingAction!('uncertain-first', 'cancel')).rejects.toThrow('MESSAGE_ALREADY_SENDING');
+ // The background runner retries the already frozen POST using its original ID.
+ const client = createChatServerClient((path, method = 'GET', body) => h.auth.apiFetch(`/v1${path}`, { method, body, assertCurrent() {} }));
+ await createChatOutboxDelivery({ store: mobileDurableOutbox, client, current: () => true, canRun: () => true, accessLost: forgetChatMessages }).run();
+ });
+ expect(posted).toHaveLength(2); expect(posted[1]).toEqual(posted[0]);
+ expect(mobileDurableOutbox.getSnapshot()[0]).toMatchObject({ state: 'failed', enqueueStarted: true });
+ await expect(chat.pendingAction!('uncertain-first', 'cancel')).rejects.toThrow('MESSAGE_ALREADY_SENDING');
+});
diff --git a/apps/mobile/src/chat/chatOutbox.ts b/apps/mobile/src/chat/chatOutbox.ts
index 96320e306a..64e76e0a12 100644
--- a/apps/mobile/src/chat/chatOutbox.ts
+++ b/apps/mobile/src/chat/chatOutbox.ts
@@ -52,6 +52,8 @@ export function createChatOutboxDelivery(deps: {
if (!deps.canRun() || !deps.current()) return;
if (!row.chat || !current(row)) continue;
const room = row.chat.roomId;
+ // A later rejection cannot disprove a previous POST whose outcome was lost.
+ const previouslyStarted = row.enqueueStarted === true;
if (blocked.has(room)) continue;
if (row.suspended || row.state === 'failed') { blocked.add(room); continue; }
const guard = () => {
@@ -83,7 +85,8 @@ export function createChatOutboxDelivery(deps: {
const recipients = input.mentions.all ? joined.map(member => member.id) : input.mentions.botIds;
input = { ...input, mentions: { all: false, botIds: [...new Set(recipients.filter(id => id !== self))] } };
}
- row = await store.update(row, { state: 'sending', error: undefined }); guard();
+ row = await store.update(row, { state: 'sending', error: undefined,
+ ...(row.chat!.body ? { enqueueStarted: true } : {}) }); guard();
const receipt = await client.send(room, input, { body: row.chat!.body, save: async body => {
guard(); row = await store.update(row, { chat: { ...row.chat!, body }, enqueueStarted: true }); guard();
} });
@@ -101,6 +104,10 @@ export function createChatOutboxDelivery(deps: {
blocked.add(room);
try {
await store.update(row, { state: refused ? 'failed' : 'queued', error: message,
+ // Only a definitive refusal with no earlier uncertain attempt releases the
+ // intent for cancellation/recomposition. Never release a known receipt.
+ ...(refused && !previouslyStarted && !row.chat!.messageId
+ ? { enqueueStarted: false, chat: { ...row.chat!, body: undefined } } : {}),
...(chatAccessLost(error) ? { suspended: true } : {}) });
if (chatAccessLost(error)) {
await suspendChatOutbox(store, room);