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): settle committed media corrections across clear

xd4c29318f333c
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/assistantFinalRetraction.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/assistantFinalRetraction.test.ts
index 88cf0faad8..bf4c0ca12a 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/assistantFinalRetraction.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/assistantFinalRetraction.test.ts
@@ -6,6 +6,7 @@ import { messages, sessions } from '../../schema';
import { tx } from '../../worker/opHandlers/tx';
import { discardPersistedAssistantMessage } from '../messages';
import * as prRefsStore from '../../../git-context/prRefsStore';
+import * as previewRows from '../../latestMessageText';
import { commitMessageMediaRefs } from '../../../cindy-media/chatAttachments';
import { onAssistantTextEvent, clearSessionPersistState, drainPersistQueue,
flushAssistantBlock, noteSessionClearBoundary } from '../../../messagePersistBroadcaster';
@@ -377,3 +378,55 @@ it.each([false, true])('reconciles replaced media without releasing another live
.toEqual((shared ? [oldHash, newHash] : [newHash]).map((hash) => ({ hash })));
expect(h.sqlite!.prepare('SELECT count(*) AS n FROM media_blobs').get()).toEqual({ n: 2 });
});
+
+
+it.each(['after-update', 'during-preview', 'row-deleted'] as const)(
+ 'settles replaced media publication when clear interrupts a committed final (%s)', async (phase) => {
+ const hash = 'a'.repeat(64);
+ const url = `cindy-media://blobs/${hash}.png`;
+ h.sqlite!.prepare("INSERT INTO media_blobs VALUES (?, '.png', 'image/png', 8, 0, 1, 1)").run(hash);
+ const actual = await vi.importActual<typeof import('../../../cindy-media/chatAttachments')>('../../../cindy-media/chatAttachments');
+ let release!: () => void;
+ const pending = new Promise<void>((resolve) => { release = resolve; });
+ vi.mocked(commitMessageMediaRefs).mockImplementationOnce(async (params, db) => {
+ await pending;
+ return actual.commitMessageMediaRefs(params, db);
+ });
+ onAssistantTextEvent('s1', { text: url, agentMessageId: 'correct-clear-media' }, null);
+ flushAssistantBlock('s1');
+ await drainPersistQueue();
+ const clear = () => {
+ const boundary = Date.now() + 1000;
+ h.sqlite!.prepare('UPDATE sessions SET cleared_at = ? WHERE id = ?').run(boundary, 's1');
+ noteSessionClearBoundary('s1', boundary);
+ release();
+ };
+ const originalTx = h.client!.tx;
+ h.client!.tx = async (name, args) => {
+ const result = await originalTx(name, args);
+ if (name === 'message.updateContent') {
+ if (phase === 'after-update') clear();
+ if (phase === 'row-deleted') {
+ h.sqlite!.prepare("DELETE FROM messages WHERE session_id = 's1'").run();
+ release();
+ }
+ }
+ return result;
+ };
+ const latest = previewRows.latestVisiblePreviewRow;
+ const preview = vi.spyOn(previewRows, 'latestVisiblePreviewRow').mockImplementationOnce(async (sessionId) => {
+ const row = await latest(sessionId);
+ if (phase === 'during-preview') clear();
+ return row;
+ });
+ h.broadcast.mockClear();
+ try {
+ onAssistantTextEvent('s1', { text: 'Corrected without media', agentMessageId: 'correct-clear-media', isFinal: true, isFullText: true }, null);
+ await drainPersistQueue();
+ await vi.mocked(commitMessageMediaRefs).mock.results[0].value;
+ expect(h.sqlite!.prepare("SELECT count(*) AS n FROM media_refs WHERE ref_kind = 'session-attachment'").get()).toEqual({ n: 0 });
+ expect(h.sqlite!.prepare('SELECT count(*) AS n FROM media_blobs').get()).toEqual({ n: 1 });
+ expect(h.broadcast.mock.calls.filter(([channel]) => channel === 'local-db:sessions:patched')).toHaveLength(0);
+ } finally { release(); preview.mockRestore(); }
+ },
+);
diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.ts
index cd2b7fa838..bf187f7511 100644
--- a/apps/desktop/src/main/localDb/ipc/messages.ts
+++ b/apps/desktop/src/main/localDb/ipc/messages.ts
@@ -205,8 +205,9 @@ async function maybeBroadcastSessionListPreview(
sessionId: string,
row: MessageRow,
ownerScope?: DataOwnerBroadcastScope | null,
+ isCurrent?: () => boolean,
): Promise<void> {
- if (!isVisibleSessionListPreviewRow(row)) return;
+ if (isCurrent?.() === false || !isVisibleSessionListPreviewRow(row)) return;
let latest: Awaited<ReturnType<typeof latestVisiblePreviewRow>>;
try {
latest = await latestVisiblePreviewRow(sessionId);
@@ -218,7 +219,7 @@ async function maybeBroadcastSessionListPreview(
});
return;
}
- if (latest?.clientId !== row.clientId) return;
+ if (isCurrent?.() === false || latest?.clientId !== row.clientId) return;
if (!isOwnerBroadcastScopeCurrent(ownerScope)) return;
const preview = extractMessagePreview(row.content, row.role);
// 不在这里落库。insert/update 事务已经把 list_preview 置空;事后 persist 无法
@@ -1619,8 +1620,7 @@ export async function updateMessageContent(
const row: MessageRow | undefined = narrow
? (await restoreTaskImageRows(dbClient, [{ ...narrow, content: serialized }]))[0]
: undefined;
- if (row) {
- if (finalSnapshot && !isCurrent()) return messageToCamel(row);
+ if (row && (!finalSnapshot || isCurrent())) {
// 挂账钩子同样覆盖"先摘要 create、后全文 update"的 tool_result 顺序
// (review P2:vendor 事件顺序一变,首现于 update 的 blob URL 若不在这里
// 挂账就永久零引用);幂等,create 时已挂的 hasRef 跳过。
@@ -1635,11 +1635,11 @@ export async function updateMessageContent(
error: err instanceof Error ? err.message : String(err),
});
}));
- await maybeBroadcastSessionListPreview(sessionId, row, ownerScope);
- if (original && isCurrent()) {
- await reconcileAssistantDerivedState(original, dbClient, isCurrent, ownerScope, false);
- }
+ await maybeBroadcastSessionListPreview(sessionId, row, ownerScope, finalSnapshot?.isCurrent);
}
+ // The correction already committed: settle its original publication even if
+ // clear/owner changed or another deletion removed the row during readback.
+ if (original) await reconcileAssistantDerivedState(original, dbClient, isCurrent, ownerScope, false);
return row ? messageToCamel(row) : null;
}