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): migrate anonymous streams and retract empty finals

xdbb195b938ba5
diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
index 6ed4850398..a68b2a0d3c 100644
--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
@@ -73,6 +73,8 @@ it('marks exact failed assistant items, including a live block, without rewritin
vi.mock('../localDb/ipc/messages.js', () => ({
broadcastMessageAgentMetaUpdate: vi.fn(async () => true),
broadcastMessageRow: vi.fn(),
+ broadcastMessageDeleted: vi.fn(),
+ discardPersistedAssistantMessage: vi.fn(async () => true),
createMessage: vi.fn(async () => ({}) as unknown),
findVisibleToolUseMessageByAliases: vi.fn(async () => null),
patchMessageAgentMetaWithResult: vi.fn(async (_sessionId, _clientId, patch) => ({
@@ -114,6 +116,8 @@ vi.mock('../device-link/broadcast-tap.js', () => ({
import {
broadcastMessageAgentMetaUpdate,
broadcastMessageRow,
+ broadcastMessageDeleted,
+ discardPersistedAssistantMessage,
createMessage,
findVisibleToolUseMessageByAliases,
patchMessageAgentMetaWithResult,
@@ -2991,6 +2995,33 @@ describe('streamed assistant final calibration', () => {
expect(vi.mocked(createMessage).mock.calls.filter(([, message]) => message.role === 'assistant')).toHaveLength(1);
});
+ it('retracts a persisted item on an empty authoritative final without disturbing the newer stream', async () => {
+ const firstId = onAssistantTextEvent(SESSION,
+ { text: 'Withdrawn draft', agentMessageId: 'msg-a' }, null);
+ flushAssistantBlock(SESSION);
+ onToolUseEvent(SESSION, { toolUseId: 'cmd-a', toolName: 'exec', input: {} }, null);
+ onAssistantTextEvent(SESSION, { text: 'Next step', agentMessageId: 'msg-b' }, null);
+ const before = getSessionTextSnapshot(SESSION);
+ onAssistantTextEvent(SESSION,
+ { text: '', isFinal: true, isFullText: true, agentMessageId: 'msg-a' }, null);
+ await flushWrites();
+ expect(updateMessageContent).not.toHaveBeenCalledWith(SESSION, firstId, '');
+ expect(discardPersistedAssistantMessage).toHaveBeenCalledWith(SESSION, firstId, expect.any(Function));
+ expect(broadcastMessageDeleted).toHaveBeenCalledWith({ sessionId: SESSION,
+ clientId: firstId, clientIds: [firstId] }, expect.anything());
+ expect(getSessionTextSnapshot(SESSION)).toEqual(before);
+ });
+
+ it('does not leave a retracted item as the completion or cost target', async () => {
+ onAssistantTextEvent(SESSION, { text: 'Withdrawn', agentMessageId: 'msg-a' }, null);
+ flushAssistantBlock(SESSION);
+ onAssistantTextEvent(SESSION,
+ { text: '', isFinal: true, isFullText: true, agentMessageId: 'msg-a' }, null);
+ expect(consumeLastAssistantPersistId(SESSION)).toBeUndefined();
+ expect(consumeLastTopLevelAssistantPersistId(SESSION)).toBeUndefined();
+ await flushWrites();
+ });
+
it('calibrates an older item without flushing or replacing the newer stream', async () => {
const firstId = onAssistantTextEvent(SESSION,
{ text: 'Incorrect long draft', agentMessageId: 'msg-a' }, null);
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/assistantFinalRetraction.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/assistantFinalRetraction.test.ts
new file mode 100644
index 0000000000..c77a59fec6
--- /dev/null
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/assistantFinalRetraction.test.ts
@@ -0,0 +1,154 @@
+/** Late authoritative empty finals retract only the rejected draft in real SQLite. */
+import Database from 'better-sqlite3';
+import { drizzle } from 'drizzle-orm/better-sqlite3';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { messages, sessions } from '../../schema';
+import { tx } from '../../worker/opHandlers/tx';
+import { discardPersistedAssistantMessage } from '../messages';
+import { onAssistantTextEvent, clearSessionPersistState, drainPersistQueue,
+ flushAssistantBlock } from '../../../messagePersistBroadcaster';
+
+const h = vi.hoisted(() => ({
+ sqlite: null as Database.Database | null,
+ client: null as {
+ drizzle: ReturnType<typeof drizzle>;
+ tx: (name: string, args: unknown) => Promise<unknown>;
+ exec: (sql: string, params?: unknown[]) => Promise<Database.RunResult>;
+ query: (sql: string, params?: unknown[]) => Promise<unknown[]>;
+ } | null,
+ broadcast: vi.fn(),
+ warn: vi.fn(),
+}));
+
+vi.mock('electron', () => ({
+ ipcMain: { handle: vi.fn() },
+ BrowserWindow: { getAllWindows: () => [{ isDestroyed: () => false, webContents: { send: h.broadcast } }] },
+}));
+vi.mock('../../../logger', () => ({
+ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: h.warn, error: vi.fn() }),
+}));
+vi.mock('../../../logger.js', () => ({
+ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: h.warn, error: vi.fn() }),
+}));
+vi.mock('../../../maker-host/codex-local-sessions', () => ({
+ importExternalCodexMessagesForSession: vi.fn(async () => undefined),
+}));
+vi.mock('../../../maker-host/claude-local-sessions', () => ({
+ importExternalClaudeCodeMessagesForSession: vi.fn(async () => undefined),
+}));
+vi.mock('../../../embedders/chat-history-embedder', () => ({
+ onMessageCreated: vi.fn(async () => undefined),
+}));
+vi.mock('../../../git-context/prRefsStore', () => ({
+ recomputePrRefsForSession: vi.fn(async () => undefined),
+ recordPrRefsForMessage: 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('../../../device-link/invoke-context', () => ({
+ isDeviceLinkInvoke: vi.fn(() => false),
+}));
+vi.mock('../../../device-link/broadcast-tap', () => ({
+ captureDataOwnerBroadcastScope: vi.fn(() => null),
+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),
+ tapWindowBroadcast: vi.fn(),
+}));
+vi.mock('../../client/current', () => ({
+ getDbClient: () => h.client,
+}));
+
+function setupDb(): void {
+ const sqlite = new Database(':memory:');
+ sqlite.exec(`
+ CREATE TABLE sessions (
+ id TEXT PRIMARY KEY,
+ cleared_at INTEGER,
+ list_preview TEXT,
+ list_preview_role TEXT,
+ list_message_count INTEGER,
+ status TEXT NOT NULL DEFAULT 'active'
+ );
+ CREATE TABLE messages (
+ id TEXT PRIMARY KEY,
+ client_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ role TEXT NOT NULL,
+ content TEXT NOT NULL,
+ tool_use_id TEXT,
+ agent_meta TEXT,
+ agent_kind TEXT,
+ created_at INTEGER NOT NULL,
+ rewind_at INTEGER
+ );
+ CREATE UNIQUE INDEX uniq_messages_session_client ON messages(session_id, client_id);
+ `);
+ sqlite.prepare("INSERT INTO sessions (id, cleared_at, status) VALUES ('s1', NULL, 'active')").run();
+ const db = drizzle(sqlite, {
+ schema: { messages, sessions },
+ });
+ h.sqlite = sqlite;
+ h.client = {
+ drizzle: db,
+ tx: async (name: string, args: unknown) => tx(sqlite, { name, args }),
+ exec: vi.fn(async (sql: string, params: unknown[] = []) => h.sqlite!.prepare(sql).run(...params)),
+ query: vi.fn(async (sql: string, params: unknown[] = []) => h.sqlite!.prepare(sql).all(...params)),
+ };
+}
+
+
+beforeEach(() => { vi.clearAllMocks(); clearSessionPersistState('s1'); setupDb(); });
+afterEach(async () => { await drainPersistQueue(); clearSessionPersistState('s1'); h.sqlite?.close(); });
+
+it('removes a flushed draft from history and broadcasts deletion while preserving the newer item', async () => {
+ const first = onAssistantTextEvent('s1', { text: 'Withdrawn draft', agentMessageId: 'a' }, null);
+ flushAssistantBlock('s1');
+ await drainPersistQueue();
+ expect(h.sqlite!.prepare('SELECT count(*) AS n FROM messages').get()).toEqual({ n: 1 });
+ h.sqlite!.prepare("UPDATE sessions SET list_preview = 'Withdrawn draft', list_message_count = 1").run();
+ const newer = onAssistantTextEvent('s1', { text: 'Next step', agentMessageId: 'b' }, null);
+ onAssistantTextEvent('s1', { text: '', agentMessageId: 'a', isFinal: true, isFullText: true }, null);
+ await drainPersistQueue();
+ expect(h.sqlite!.prepare('SELECT count(*) AS n FROM messages WHERE client_id = ?').get(first)).toEqual({ n: 0 });
+ expect(h.broadcast).toHaveBeenCalledWith('local-db:messages:deleted', {
+ sessionId: 's1', clientId: first, clientIds: [first],
+ });
+ expect(h.sqlite!.prepare('SELECT list_preview, list_message_count FROM sessions').get())
+ .toEqual({ list_preview: null, list_message_count: null });
+ // Repeated final events must not recreate the rejected draft.
+ onAssistantTextEvent('s1', { text: '', agentMessageId: 'a', isFinal: true, isFullText: true }, null);
+ flushAssistantBlock('s1');
+ await drainPersistQueue();
+ expect(h.sqlite!.prepare('SELECT client_id, content FROM messages').all())
+ .toEqual([{ client_id: newer, content: 'Next step' }]);
+});
+
+it('does not retract a different role, session, hidden row or stale boundary', async () => {
+ const insert = h.sqlite!.prepare('INSERT INTO messages (id, client_id, session_id, role, content, created_at, rewind_at) VALUES (?, ?, ?, ?, ?, 1, ?)');
+ insert.run('user', 'user', 's1', 'user', '"hello"', null);
+ insert.run('other', 'other', 's2', 'assistant', '"hello"', null);
+ insert.run('hidden', 'hidden', 's1', 'assistant', '"hello"', 2);
+ insert.run('stale', 'stale', 's1', 'assistant', '"hello"', null);
+ for (const id of ['user', 'other', 'hidden', 'missing']) {
+ expect(await discardPersistedAssistantMessage('s1', id, () => true)).toBe(false);
+ }
+ let checks = 0;
+ expect(await discardPersistedAssistantMessage('s1', 'stale', () => ++checks === 1)).toBe(false);
+ expect(h.sqlite!.prepare('SELECT count(*) AS n FROM messages').get()).toEqual({ n: 4 });
+});
+
+it('keeps a row changed while the exact-row rollback was being queued', async () => {
+ h.sqlite!.prepare("INSERT INTO messages (id, client_id, session_id, role, content, created_at) VALUES ('a', 'a', 's1', 'assistant', ?, 1)").run(JSON.stringify('draft'));
+ const original = h.client!.tx;
+ h.client!.tx = async (name, args) => {
+ h.sqlite!.prepare("UPDATE messages SET content = ? WHERE client_id = 'a'").run(JSON.stringify('edited'));
+ return original(name, args);
+ };
+ expect(await discardPersistedAssistantMessage('s1', 'a', () => true)).toBe(false);
+ expect(h.sqlite!.prepare('SELECT content FROM messages').get()).toEqual({ content: '"edited"' });
+});
diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.ts
index 6bd50e6419..da5baef640 100644
--- a/apps/desktop/src/main/localDb/ipc/messages.ts
+++ b/apps/desktop/src/main/localDb/ipc/messages.ts
@@ -1461,6 +1461,32 @@ export async function supersedeRetriedUserTurn(
return clientIds;
}
+/** 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.
+ */
+export async function discardPersistedAssistantMessage(
+ sessionId: string,
+ clientId: string,
+ isCurrent: () => boolean,
+): Promise<boolean> {
+ const ownerScope = captureOwnerBroadcastScope();
+ const dbClient = getDbClient();
+ if (!isCurrent() || !isOwnerBroadcastScopeCurrent(ownerScope)) return false;
+ const [row] = await dbClient.drizzle.select().from(messages).where(and(
+ eq(messages.sessionId, sessionId), eq(messages.clientId, clientId),
+ eq(messages.role, 'assistant'), isNull(messages.rewindAt),
+ )).limit(1);
+ if (!row || !isCurrent() || !isOwnerBroadcastScopeCurrent(ownerScope)) return false;
+ const result = await dbClient.tx('message.insert', {
+ id: row.id, clientId: row.clientId, sessionId: row.sessionId,
+ role: row.role, content: row.content, toolUseId: row.toolUseId,
+ agentMeta: row.agentMeta, agentKind: row.agentKind, createdAt: row.createdAt,
+ guarded: false, publication: 'rollback',
+ });
+ return result.changes > 0;
+}
+
export async function updateMessageContent(
sessionId: string,
clientId: string,
diff --git a/apps/desktop/src/main/messagePersistBroadcaster.ts b/apps/desktop/src/main/messagePersistBroadcaster.ts
index 7827207e9f..4a67f7cea0 100644
--- a/apps/desktop/src/main/messagePersistBroadcaster.ts
+++ b/apps/desktop/src/main/messagePersistBroadcaster.ts
@@ -37,6 +37,8 @@ import { desc, eq } from 'drizzle-orm';
import {
broadcastMessageRow,
+ broadcastMessageDeleted,
+ discardPersistedAssistantMessage,
broadcastMessageAgentMetaUpdate,
createMessage as createDbMessage,
findVisibleToolUseMessageByAliases,
@@ -2246,6 +2248,14 @@ function assembleAssistantTextEvent(
const isCurrentBoundary = () => clearBoundaryBySession.get(sessionId) === clearBoundary;
enqueueWrite(`assistant_item_final:${sessionId}:${linkedPersistId}`, async (ownerScope) => {
if (!isCurrentBoundary()) return;
+ if (!visible) {
+ const discarded = await discardPersistedAssistantMessage(sessionId, linkedPersistId,
+ () => isCurrentBoundary() && isOwnerScopeCurrent(ownerScope));
+ if (discarded && isCurrentBoundary() && isOwnerScopeCurrent(ownerScope)) {
+ broadcastMessageDeleted({ sessionId, clientId: linkedPersistId, clientIds: [linkedPersistId] }, ownerScope);
+ }
+ return;
+ }
const updated = await updateDbMessageContent(sessionId, linkedPersistId, visible);
if (!isCurrentBoundary() || !isOwnerScopeCurrent(ownerScope)) return;
if (updated) broadcastMessageRow(sessionId, updated, ownerScope);
@@ -2256,7 +2266,13 @@ function assembleAssistantTextEvent(
}
}
});
- // Preserve the newer stream and the turn's existing completion/cost target.
+ if (!visible && lastTopLevelAssistantPersistIdBySession.get(sessionId) === linkedPersistId) {
+ lastTopLevelAssistantPersistIdBySession.delete(sessionId);
+ }
+ if (!visible && lastAssistantPersistIdBySession.get(sessionId) === linkedPersistId) {
+ lastAssistantPersistIdBySession.delete(sessionId);
+ }
+ // Preserve the newer stream and its completion/cost target.
return linkedPersistId;
}
if (
diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
index 2d4144eb6d..608ee09493 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -831,6 +831,23 @@ describe('remoteSessionStore', () => {
})).toBe(false);
});
+ it('removes a rejected persisted draft while a newer assistant keeps streaming', () => {
+ vi.useFakeTimers();
+ try {
+ remoteSessionStore.setMessages('s1', [{ ...message('host-a', 's1'), clientId: 'item-a', content: 'Withdrawn' }]);
+ pushMakerText('s1', 'item-b', 'Next', false);
+ vi.runOnlyPendingTimers();
+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:deleted', {
+ sessionId: 's1', clientId: 'item-a', clientIds: ['item-a'],
+ });
+ pushMakerText('s1', undefined, ' tail', false);
+ vi.runOnlyPendingTimers();
+ expect(remoteSessionStore.getMessages('s1')).toEqual([expect.objectContaining({
+ clientId: 'item-b', content: 'Next tail', agentMeta: expect.objectContaining({ isStreaming: true }),
+ })]);
+ } finally { vi.useRealTimers(); }
+ });
+
it('removes an orphan task update even when its deleted message is not cached', () => {
remoteSessionStore.setMessages('s1', [message('m1', 's1')]);
pushMakerTaskUpdate('s1', 'orphan-task');
@@ -897,6 +914,29 @@ describe('remoteSessionStore', () => {
} finally { vi.useRealTimers(); }
});
+ it('migrates a short anonymous stream when its DB row arrives before the identified final', () => {
+ vi.useFakeTimers();
+ try {
+ pushMakerText('s1', undefined, 'Sure', false);
+ vi.runOnlyPendingTimers();
+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:created', {
+ sessionId: 's1', message: { ...message('host-a', 's1'), clientId: 'item-a', content: 'Sure, checking' },
+ });
+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(2);
+ remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {
+ sessionId: 's1', persistId: 'item-a', event: {
+ type: 'text', data: { text: 'Sure, checked', isFinal: true, isFullText: true },
+ },
+ });
+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(1);
+ pushMakerText('s1', undefined, ' tail', false);
+ vi.runOnlyPendingTimers();
+ expect(remoteSessionStore.getMessages('s1')).toEqual([expect.objectContaining({
+ id: 'host-a', clientId: 'item-a', content: 'Sure, checked tail',
+ })]);
+ } finally { vi.useRealTimers(); }
+ });
+
it('still accepts a legacy final full-text event after its partial row was persisted', () => {
remoteSessionStore.setMessages('s1', [{
...message('host-id', 's1'), clientId: 'legacy-id', content: 'partial',
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index 8804522b82..c70d80b167 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -2747,6 +2747,7 @@ function mergeRemoteTextEvent(
? previousStreamingClientId
: undefined;
const clientIdResolution = finalReusesExistingItem && normalizedPersistId
+ && (!previousStreamingClientId || !isGeneratedStreamingClientId(previousStreamingClientId))
? { clientId: normalizedPersistId, changed: false }
: streamingClientIdFor(sessionId, persistId);
const { clientId } = clientIdResolution;