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): reconcile projections after late final corrections

xd2f3093169e0a
diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
index a68b2a0d3c..6d7b4be328 100644
--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
@@ -2727,7 +2727,8 @@ describe('assistant isFinal burst DUP-SKIP(P1:main 对称去重,防重复 isFina
);
expect(lateFinalId).toBe(persistId);
await flushWrites();
- expect(updateMessageContent).toHaveBeenCalledWith(SESSION, persistId, '选哪个?');
+ expect(updateMessageContent).toHaveBeenCalledWith(SESSION, persistId, '选哪个?', undefined,
+ expect.objectContaining({ isCurrent: expect.any(Function) }));
expect(broadcastMessageRow).toHaveBeenCalled();
const assistantCreates = vi.mocked(createMessage).mock.calls
.filter(([, message]) => message.role === 'assistant');
@@ -2915,7 +2916,8 @@ describe('stale-idle assistant late final identity', () => {
const assistantCreates = (createMessage as unknown as { mock: { calls: unknown[][] } }).mock.calls
.filter((c) => (c[1] as { role?: string }).role === 'assistant');
expect(assistantCreates).toHaveLength(1);
- expect(updateMessageContent).toHaveBeenCalledWith(SESSION, persistId, 'partial output');
+ expect(updateMessageContent).toHaveBeenCalledWith(SESSION, persistId, 'partial output', undefined,
+ expect.objectContaining({ isCurrent: expect.any(Function) }));
expect(patchMessageAgentMetaWithResult).not.toHaveBeenCalled();
expect(broadcastMessageRow).toHaveBeenCalled();
});
@@ -3035,7 +3037,8 @@ describe('streamed assistant final calibration', () => {
{ model: 'test-model' })).toBe(firstId);
expect(getSessionTextSnapshot(SESSION)).toEqual(before);
await flushWrites();
- expect(updateMessageContent).toHaveBeenCalledWith(SESSION, firstId, 'Corrected');
+ expect(updateMessageContent).toHaveBeenCalledWith(SESSION, firstId, 'Corrected', undefined,
+ expect.objectContaining({ isCurrent: expect.any(Function) }));
expect(patchMessageAgentMetaWithResult).toHaveBeenCalledWith(SESSION, firstId, { model: 'test-model' });
expect(broadcastMessageRow).toHaveBeenCalled();
expect(vi.mocked(createMessage).mock.calls.filter(([, message]) => message.role === 'assistant')).toHaveLength(1);
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 9d382585d7..88cf0faad8 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 { commitMessageMediaRefs } from '../../../cindy-media/chatAttachments';
import { onAssistantTextEvent, clearSessionPersistState, drainPersistQueue,
flushAssistantBlock, noteSessionClearBoundary } from '../../../messagePersistBroadcaster';
@@ -40,14 +41,10 @@ vi.mock('../../../maker-host/claude-local-sessions', () => ({
vi.mock('../../../embedders/chat-history-embedder', () => ({
onMessageCreated: vi.fn(async () => undefined),
}));
-vi.mock('../../../cindy-media/chatAttachments', () => ({
- commitMessageMediaRefs: vi.fn(async () => null),
- collectCindyMediaHashes: vi.fn(() => []),
-}));
-vi.mock('../../../cindy-media/ledger', () => ({
- removeRefs: vi.fn(async () => undefined),
- removeSessionAttachmentRefIfUnreferencedByLiveMessage: vi.fn(async () => undefined),
-}));
+vi.mock('../../../cindy-media/chatAttachments', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../../cindy-media/chatAttachments')>();
+ return { ...actual, commitMessageMediaRefs: vi.fn(actual.commitMessageMediaRefs) };
+});
vi.mock('../../../device-link/invoke-context', () => ({
isDeviceLinkInvoke: vi.fn(() => false),
}));
@@ -84,6 +81,16 @@ function setupDb(): void {
rewind_at INTEGER
);
CREATE UNIQUE INDEX uniq_messages_session_client ON messages(session_id, client_id);
+ CREATE TABLE media_blobs (
+ hash TEXT PRIMARY KEY, ext TEXT NOT NULL, mime_type TEXT NOT NULL,
+ bytes INTEGER NOT NULL, is_cache INTEGER NOT NULL DEFAULT 0,
+ created_at INTEGER NOT NULL, last_access_at INTEGER NOT NULL
+ );
+ CREATE TABLE media_refs (
+ id TEXT PRIMARY KEY, hash TEXT NOT NULL REFERENCES media_blobs(hash),
+ ref_kind TEXT NOT NULL, ref_id TEXT NOT NULL, origin_session_id TEXT,
+ origin_kind TEXT, origin_id TEXT, label TEXT, created_at INTEGER NOT NULL
+ );
CREATE TABLE session_pr_refs (
id TEXT PRIMARY KEY, session_id TEXT NOT NULL, owner TEXT NOT NULL,
repo TEXT NOT NULL, pr_number INTEGER NOT NULL, url TEXT NOT NULL,
@@ -246,3 +253,127 @@ it('does not restore pre-clear PR references when retraction cleanup resumes aft
expect(await prRefsStore.listPrRefs('s1')).toHaveLength(0);
} finally { release(); spy.mockRestore(); }
});
+
+
+it.each(['none', 'previous', 'newer'] as const)(
+ 'broadcasts the surviving canonical list preview after retracting the draft (%s)', async (survivor) => {
+ if (survivor === 'previous') {
+ h.sqlite!.prepare("INSERT INTO messages (id, client_id, session_id, role, content, created_at) VALUES ('u', 'u', 's1', 'user', ?, 1)").run('Previous question');
+ }
+ onAssistantTextEvent('s1', { text: 'Rejected draft', agentMessageId: 'a' }, null);
+ flushAssistantBlock('s1');
+ await drainPersistQueue();
+ if (survivor === 'newer') {
+ onAssistantTextEvent('s1', { text: 'Newer answer', agentMessageId: 'b' }, null);
+ flushAssistantBlock('s1');
+ await drainPersistQueue();
+ }
+ h.broadcast.mockClear();
+ onAssistantTextEvent('s1', { text: '', agentMessageId: 'a', isFinal: true, isFullText: true }, null);
+ await drainPersistQueue();
+ const patches = h.broadcast.mock.calls.filter(([channel]) => channel === 'local-db:sessions:patched');
+ expect(patches.at(-1)?.[1]).toEqual({ sessionId: 's1', patch: {
+ preview: survivor === 'none' ? null : survivor === 'previous' ? 'Previous question' : 'Newer answer',
+ } });
+ },
+);
+
+it.each(['Corrected without a link', 'https://github.com/o/r/pull/3'])(
+ 'reconciles PR references after nonempty final correction and a delayed original hook (%s)', async (text) => {
+ onAssistantTextEvent('s1', { text: 'https://github.com/o/r/pull/1', agentMessageId: 'keep' }, null);
+ flushAssistantBlock('s1');
+ await drainPersistQueue();
+ let release!: () => void;
+ const pending = new Promise<void>((resolve) => { release = resolve; });
+ const original = prRefsStore.recordPrRefsForMessage;
+ const hook = vi.spyOn(prRefsStore, 'recordPrRefsForMessage').mockImplementationOnce(async (msg) => {
+ await pending;
+ await original(msg);
+ });
+ let corrected!: () => void;
+ const written = new Promise<void>((resolve) => { corrected = resolve; });
+ const originalTx = h.client!.tx;
+ h.client!.tx = async (name, args) => {
+ const result = await originalTx(name, args);
+ if (name === 'message.updateContent') corrected();
+ return result;
+ };
+ try {
+ onAssistantTextEvent('s1', { text: 'https://github.com/o/r/pull/2', agentMessageId: 'correct' }, null);
+ flushAssistantBlock('s1');
+ await drainPersistQueue();
+ onAssistantTextEvent('s1', { text, agentMessageId: 'correct', isFinal: true, isFullText: true }, null);
+ await written;
+ release();
+ await drainPersistQueue();
+ await hook.mock.results[0].value;
+ expect((await prRefsStore.listPrRefs('s1')).map((ref) => ref.prNumber).sort())
+ .toEqual(text.includes('/pull/') ? [1, 3] : [1]);
+ } finally { release(); hook.mockRestore(); }
+ },
+);
+
+it.each([{ shared: false, clear: false }, { shared: true, clear: false }, { shared: false, clear: true }])(
+ 'settles pending media publication before reconciling withdrawn references (%j)', async ({ shared, clear }) => {
+ 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);
+ if (shared) {
+ h.sqlite!.prepare("INSERT INTO messages (id, client_id, session_id, role, content, created_at) VALUES ('keep-media', 'keep-media', 's1', 'user', ?, 1)").run(url);
+ }
+ 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);
+ });
+ let deleted!: () => void;
+ const rollback = new Promise<void>((resolve) => { deleted = resolve; });
+ const originalTx = h.client!.tx;
+ h.client!.tx = async (name, args) => {
+ const result = await originalTx(name, args);
+ if ((args as { publication?: string }).publication === 'rollback') deleted();
+ return result;
+ };
+ try {
+ onAssistantTextEvent('s1', { text: url, agentMessageId: 'withdraw-media' }, null);
+ flushAssistantBlock('s1');
+ await drainPersistQueue();
+ onAssistantTextEvent('s1', { text: '', agentMessageId: 'withdraw-media', isFinal: true, isFullText: true }, null);
+ await rollback;
+ if (clear) {
+ const boundary = Date.now() + 1000;
+ h.sqlite!.prepare('UPDATE sessions SET cleared_at = ? WHERE id = ?').run(boundary, 's1');
+ noteSessionClearBoundary('s1', boundary);
+ }
+ release();
+ 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: shared ? 1 : 0 });
+ expect(h.sqlite!.prepare('SELECT count(*) AS n FROM media_blobs').get()).toEqual({ n: 1 });
+ } finally { release(); }
+});
+
+
+it.each([false, true])('reconciles replaced media without releasing another live message reference (shared=%s)', async (shared) => {
+ const oldHash = 'a'.repeat(64);
+ const newHash = 'b'.repeat(64);
+ const oldUrl = `cindy-media://blobs/${oldHash}.png`;
+ const newUrl = `cindy-media://blobs/${newHash}.png`;
+ for (const hash of [oldHash, newHash]) {
+ h.sqlite!.prepare("INSERT INTO media_blobs VALUES (?, '.png', 'image/png', 8, 0, 1, 1)").run(hash);
+ }
+ if (shared) {
+ h.sqlite!.prepare("INSERT INTO messages (id, client_id, session_id, role, content, created_at) VALUES ('keep-media', 'keep-media', 's1', 'user', ?, 1)").run(oldUrl);
+ }
+ onAssistantTextEvent('s1', { text: oldUrl, agentMessageId: 'replace-media' }, null);
+ flushAssistantBlock('s1');
+ await drainPersistQueue();
+ onAssistantTextEvent('s1', { text: newUrl, agentMessageId: 'replace-media', isFinal: true, isFullText: true }, null);
+ await drainPersistQueue();
+ expect(h.sqlite!.prepare("SELECT hash FROM media_refs WHERE ref_kind = 'session-attachment' ORDER BY hash").all())
+ .toEqual((shared ? [oldHash, newHash] : [newHash]).map((hash) => ({ hash })));
+ expect(h.sqlite!.prepare('SELECT count(*) AS n FROM media_blobs').get()).toEqual({ n: 2 });
+});
diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.ts
index 5c612d31a2..cd2b7fa838 100644
--- a/apps/desktop/src/main/localDb/ipc/messages.ts
+++ b/apps/desktop/src/main/localDb/ipc/messages.ts
@@ -89,9 +89,31 @@ function notAutoResumeAgentMetaSql() {
return sql`(${messages.agentMeta} IS NULL OR CASE WHEN json_valid(${messages.agentMeta}) THEN json_extract(${messages.agentMeta}, '$.autoResume') END IS NOT 1)`;
}
-// Publication hooks stay asynchronous for normal messages. A terminal retraction
-// waits for its exact row's hook before rebuilding derived PR references.
+// Normal publication stays non-blocking. Authoritative corrections/retractions
+// settle the exact row's create/update hooks before reconciling derived state.
const pendingPrRefWrites = new WeakMap<DbClient, Map<string, Promise<void>>>();
+const pendingMediaWrites = new WeakMap<DbClient, Map<string, Set<Promise<void>>>>();
+
+function trackMessageMediaWrite(dbClient: DbClient, rowId: string, write: Promise<void>): Promise<void> {
+ let rows = pendingMediaWrites.get(dbClient);
+ if (!rows) {
+ rows = new Map();
+ pendingMediaWrites.set(dbClient, rows);
+ }
+ let writes = rows.get(rowId);
+ if (!writes) {
+ writes = new Set();
+ rows.set(rowId, writes);
+ }
+ writes.add(write);
+ const tracked = writes;
+ const trackedRows = rows;
+ void write.then(() => {
+ tracked.delete(write);
+ if (tracked.size === 0 && trackedRows.get(rowId) === tracked) trackedRows.delete(rowId);
+ });
+ return write;
+}
type MessageRow = typeof messages.$inferSelect;
type MessageRowWithRowid = MessageRow & { rowid: number };
@@ -1465,6 +1487,58 @@ export async function supersedeRetriedUserTurn(
return clientIds;
}
+/** Reconcile only the corrected row's derived state against current live history. */
+async function reconcileAssistantDerivedState(
+ row: MessageRow,
+ dbClient: DbClient,
+ isCurrent: () => boolean,
+ ownerScope: DataOwnerBroadcastScope | null,
+ refreshPreview: boolean,
+): Promise<void> {
+ await Promise.all([
+ pendingPrRefWrites.get(dbClient)?.get(row.id),
+ ...(pendingMediaWrites.get(dbClient)?.get(row.id) ?? []),
+ ]);
+ try {
+ if (isCurrent()) await recomputePrRefsForSession(row.sessionId, { dbClient, isCurrent });
+ } catch (error) {
+ log.warn('assistant correction PR reference reconciliation failed', {
+ sessionId: row.sessionId, clientId: row.clientId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ // Cleanup belongs to the committed mutation even if clear/owner changes while
+ // publication settles. Use its captured DB and atomic live-message predicate;
+ // never republish derived state into the replacement scope.
+ for (const hash of collectCindyMediaHashes(row.content)) {
+ try {
+ // Existing ledger lock + atomic live-message predicate protect shared blobs.
+ await removeSessionAttachmentRefIfUnreferencedByLiveMessage(
+ { sessionId: row.sessionId, hash }, dbClient.drizzle,
+ );
+ } catch (error) {
+ log.warn('assistant correction media reference reconciliation failed', {
+ sessionId: row.sessionId, clientId: row.clientId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ if (!refreshPreview || !isCurrent()) return;
+ try {
+ const latest = await latestVisiblePreviewRow(row.sessionId);
+ if (!isCurrent()) return;
+ broadcastOwnedPayload('local-db:sessions:patched', {
+ sessionId: row.sessionId,
+ patch: { preview: extractMessagePreview(latest?.content, latest?.role) },
+ }, ownerScope);
+ } catch (error) {
+ log.warn('assistant retraction preview refresh failed', {
+ sessionId: row.sessionId, clientId: row.clientId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+}
+
/** Retract an assistant draft rejected by its authoritative empty final.
* Reuse the exact-row publication rollback so preview/count invalidation is
* atomic and a concurrent edit or replacement can never be removed.
@@ -1489,12 +1563,8 @@ export async function discardPersistedAssistantMessage(
guarded: false, publication: 'rollback',
});
if (result.changes === 0) return false;
- await pendingPrRefWrites.get(dbClient)?.get(row.id);
- if (isCurrent() && isOwnerBroadcastScopeCurrent(ownerScope)) {
- await recomputePrRefsForSession(sessionId, {
- dbClient, isCurrent: () => isCurrent() && isOwnerBroadcastScopeCurrent(ownerScope),
- });
- }
+ await reconcileAssistantDerivedState(row, dbClient,
+ () => isCurrent() && isOwnerBroadcastScopeCurrent(ownerScope), ownerScope, true);
return true;
}
@@ -1503,10 +1573,17 @@ export async function updateMessageContent(
clientId: string,
content: unknown,
autoReviewAnswer?: { text: string; acceptedAt: number },
+ finalSnapshot?: { isCurrent: () => boolean },
): Promise<Message | null> {
const ownerScope = captureOwnerBroadcastScope();
const dbClient = getDbClient();
const db = dbClient.drizzle;
+ const isCurrent = () => isOwnerBroadcastScopeCurrent(ownerScope) && finalSnapshot?.isCurrent() !== false;
+ const [original] = finalSnapshot
+ ? await db.select().from(messages).where(and(eq(messages.sessionId, sessionId),
+ eq(messages.clientId, clientId), eq(messages.role, 'assistant'), isNull(messages.rewindAt))).limit(1)
+ : [];
+ if (finalSnapshot && (!original || !isCurrent())) return null;
const serialized = safeStringify(content);
if (autoReviewAnswer !== undefined) {
// Host-only interaction result: keep content and its authorization evidence atomic.
@@ -1543,21 +1620,25 @@ export async function updateMessageContent(
? (await restoreTaskImageRows(dbClient, [{ ...narrow, content: serialized }]))[0]
: undefined;
if (row) {
+ if (finalSnapshot && !isCurrent()) return messageToCamel(row);
// 挂账钩子同样覆盖"先摘要 create、后全文 update"的 tool_result 顺序
// (review P2:vendor 事件顺序一变,首现于 update 的 blob URL 若不在这里
// 挂账就永久零引用);幂等,create 时已挂的 hasRef 跳过。
- void commitMessageMediaRefs({
+ trackMessageMediaWrite(dbClient, row.id, commitMessageMediaRefs({
sessionId,
role: row.role,
content: row.content,
- }).catch((err) => {
+ }).then(() => undefined).catch((err) => {
log.warn('message media ref commit failed (update)', {
sessionId,
clientId,
error: err instanceof Error ? err.message : String(err),
});
- });
+ }));
await maybeBroadcastSessionListPreview(sessionId, row, ownerScope);
+ if (original && isCurrent()) {
+ await reconcileAssistantDerivedState(original, dbClient, isCurrent, ownerScope, false);
+ }
}
return row ? messageToCamel(row) : null;
}
@@ -1864,8 +1945,8 @@ export async function createMessage(
opts !== undefined &&
Object.prototype.hasOwnProperty.call(opts, 'expectedClearBoundaryMs');
if (!opts?.deferMediaRefs) {
- if (shouldAwaitMediaRefs) await commitMediaRefs();
- else void commitMediaRefs();
+ const mediaWrite = trackMessageMediaWrite(dbClient, row.id, commitMediaRefs());
+ if (shouldAwaitMediaRefs) await mediaWrite;
}
// Broadcast 给所有 renderer window — 用于 main 端创建消息 (e.g. feishu /ctr
// 接管路径下 persistUserMessage / persistAssistantMessage) 时让 renderer
diff --git a/apps/desktop/src/main/messagePersistBroadcaster.ts b/apps/desktop/src/main/messagePersistBroadcaster.ts
index 4a67f7cea0..0f1ad367e9 100644
--- a/apps/desktop/src/main/messagePersistBroadcaster.ts
+++ b/apps/desktop/src/main/messagePersistBroadcaster.ts
@@ -2256,7 +2256,9 @@ function assembleAssistantTextEvent(
}
return;
}
- const updated = await updateDbMessageContent(sessionId, linkedPersistId, visible);
+ const updated = await updateDbMessageContent(sessionId, linkedPersistId, visible, undefined, {
+ isCurrent: () => isCurrentBoundary() && isOwnerScopeCurrent(ownerScope),
+ });
if (!isCurrentBoundary() || !isOwnerScopeCurrent(ownerScope)) return;
if (updated) broadcastMessageRow(sessionId, updated, ownerScope);
if (agentMeta) {
@@ -2306,6 +2308,8 @@ function assembleAssistantTextEvent(
sessionId,
lateFinalCandidate.persistId,
visible,
+ undefined,
+ { isCurrent: () => isCandidateCurrent() && isOwnerScopeCurrent(ownerScope) },
);
if (updated && isCandidateCurrent()) {
lateFinalCandidate.text = visible;
@@ -2376,6 +2380,8 @@ function assembleAssistantTextEvent(
sessionId,
boundaryFlushed.persistId,
visible,
+ undefined,
+ { isCurrent: () => lastBoundaryFlushedAssistantBySession.get(sessionId) === boundaryFlushed && isOwnerScopeCurrent(ownerScope) },
);
if (updated) {
// 缓存已落库的全文:重复投递同一份快照时不再重复 UPDATE。
diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
index 608ee09493..5ab13916a4 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -2412,6 +2412,20 @@ describe('remoteSessionStore', () => {
expect(remoteSessionStore.getSessionListMessagePreview('s1')).toBe('');
});
+ it.each([null, 'previous user', 'newer reply'])('uses the canonical preview after a draft is retracted: %s', (preview) => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { preview: 'rejected draft' })]);
+ remoteSessionStore.setMessages('s1', [{ ...message('draft', 's1'), content: 'rejected draft' }]);
+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:sessions:patched', {
+ sessionId: 's1', patch: { preview },
+ });
+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:deleted', {
+ sessionId: 's1', clientIds: ['draft'],
+ });
+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(0);
+ expect(remoteSessionStore.getSessions().find((row) => row.id === 's1')?.preview).toBe(preview);
+ expect(remoteSessionStore.getSessionListMessagePreview('s1')).toBe(preview ?? undefined);
+ });
+
it('tracks which session metadata the message window has been synced against', () => {
const meta = session('s1', {
updatedAt: '2026-01-01T00:00:01.000Z',