Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(chat): preserve later deltas and clean retracted PR references
xd2dd8b2da0614
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/assistantFinalRetraction.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/assistantFinalRetraction.test.tsindex c77a59fec6..05603ec853 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/assistantFinalRetraction.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/assistantFinalRetraction.test.ts@@ -5,6 +5,7 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest';import { messages, sessions } from '../../schema';import { tx } from '../../worker/opHandlers/tx';import { discardPersistedAssistantMessage } from '../messages';+import * as prRefsStore from '../../../git-context/prRefsStore';import { onAssistantTextEvent, clearSessionPersistState, drainPersistQueue,flushAssistantBlock } from '../../../messagePersistBroadcaster';@@ -39,10 +40,6 @@ vi.mock('../../../maker-host/claude-local-sessions', () => ({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(() => []),@@ -87,6 +84,12 @@ function setupDb(): void {rewind_at INTEGER);CREATE UNIQUE INDEX uniq_messages_session_client ON messages(session_id, client_id);+ 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,+ first_seen_at INTEGER NOT NULL, last_seen_at INTEGER NOT NULL,+ UNIQUE(session_id, owner, repo, pr_number)+ );`);sqlite.prepare("INSERT INTO sessions (id, cleared_at, status) VALUES ('s1', NULL, 'active')").run();const db = drizzle(sqlite, {@@ -152,3 +155,48 @@ it('keeps a row changed while the exact-row rollback was being queued', async ()expect(await discardPersistedAssistantMessage('s1', 'a', () => true)).toBe(false);expect(h.sqlite!.prepare('SELECT content FROM messages').get()).toEqual({ content: '"edited"' });});+++it('removes the withdrawn draft PR reference but retains a surviving message reference', async () => {+ onAssistantTextEvent('s1', { text: 'https://github.com/o/r/pull/1', agentMessageId: 'keep' }, null);+ flushAssistantBlock('s1');+ onAssistantTextEvent('s1', { text: 'https://github.com/o/r/pull/2', agentMessageId: 'withdraw' }, null);+ flushAssistantBlock('s1');+ await drainPersistQueue();+ expect((await prRefsStore.listPrRefs('s1')).map((ref) => ref.prNumber).sort()).toEqual([1, 2]);+ onAssistantTextEvent('s1', { text: '', agentMessageId: 'withdraw', isFinal: true, isFullText: true }, null);+ await drainPersistQueue();+ expect((await prRefsStore.listPrRefs('s1')).map((ref) => ref.prNumber)).toEqual([1]);+});++it('orders retraction cleanup after the original asynchronous PR publication hook', async () => {+ 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 retracted!: () => void;+ const rollback = new Promise<void>((resolve) => { retracted = 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') retracted();+ return result;+ };+ try {+ onAssistantTextEvent('s1', { text: 'https://github.com/o/r/pull/2', agentMessageId: 'withdraw' }, null);+ flushAssistantBlock('s1');+ await drainPersistQueue();+ expect(hook).toHaveBeenCalledTimes(1);+ onAssistantTextEvent('s1', { text: '', agentMessageId: 'withdraw', isFinal: true, isFullText: true }, null);+ await rollback;+ release();+ await drainPersistQueue();+ await pending;+ // Await the hook itself too, so a late stale write cannot hide behind the assertion.+ await hook.mock.results[0].value;+ expect(await prRefsStore.listPrRefs('s1')).toHaveLength(0);+ } finally { release(); hook.mockRestore(); }+});diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.tsindex da5baef640..749861b4bb 100644--- a/apps/desktop/src/main/localDb/ipc/messages.ts+++ b/apps/desktop/src/main/localDb/ipc/messages.ts@@ -89,6 +89,10 @@ 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.+const pendingPrRefWrites = new WeakMap<DbClient, Map<string, Promise<void>>>();+type MessageRow = typeof messages.$inferSelect;type MessageRowWithRowid = MessageRow & { rowid: number };type DataOwnerBroadcastScope = ReturnType<typeof broadcastTap.captureDataOwnerBroadcastScope>;@@ -1484,7 +1488,12 @@ export async function discardPersistedAssistantMessage(agentMeta: row.agentMeta, agentKind: row.agentKind, createdAt: row.createdAt,guarded: false, publication: 'rollback',});- return result.changes > 0;+ if (result.changes === 0) return false;+ await pendingPrRefWrites.get(dbClient)?.get(row.id);+ if (isCurrent() && isOwnerBroadcastScopeCurrent(ownerScope)) {+ await recomputePrRefsForSession(sessionId);+ }+ return true;}export async function updateMessageContent(@@ -1874,9 +1883,18 @@ export async function createMessage(});// session-git-pr-context hook —— fire-and-forget。内部限定 user/assistant 角色,// 每条消息跑一次锚定正则线性扫描(开销可忽略);失败仅 log warn。- void recordPrRefsForMessage(msg).catch(() => {+ const prRefsWrite = recordPrRefsForMessage(msg).catch(() => {// recordPrRefsForMessage 内部已 try/catch,此处兜底防御 refactor 漏网异常。});+ let pendingPrRefs = pendingPrRefWrites.get(dbClient);+ if (!pendingPrRefs) {+ pendingPrRefs = new Map();+ pendingPrRefWrites.set(dbClient, pendingPrRefs);+ }+ pendingPrRefs.set(msg.id, prRefsWrite);+ void prRefsWrite.then(() => {+ if (pendingPrRefs.get(msg.id) === prRefsWrite) pendingPrRefs.delete(msg.id);+ });return msg;}diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.tsindex ba84b7a969..06d4f76679 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts@@ -143,6 +143,7 @@ let onDeviceLinkStatusChanged: ((data: unknown) => void) | undefined;let onPresenceChanged: ((data: unknown) => void) | undefined;let onRemotePush: ((data: unknown, ownerStamp?: unknown) => void) | undefined;let onDbMessageCreated: ((data: unknown) => void) | undefined;+let onDbMessageDeleted: ((data: unknown) => void) | undefined;let onErrorPersisted: ((data: unknown, ownerStamp?: unknown) => void) | undefined;let onInputProjection: ((data: unknown) => void) | undefined;let onInteractionRequest: ((data: unknown) => void) | undefined;@@ -261,6 +262,7 @@ function installElectronBridge(): void {onPresenceChanged = undefined;onRemotePush = undefined;onDbMessageCreated = undefined;+ onDbMessageDeleted = undefined;onErrorPersisted = undefined;onInputProjection = undefined;onInteractionRequest = undefined;@@ -330,6 +332,10 @@ function installElectronBridge(): void {},localDb: {messages: {+ onDeleted: (cb: (data: unknown) => void) => {+ onDbMessageDeleted = cb;+ return vi.fn();+ },onCreated: (cb: (data: unknown) => void) => {onDbMessageCreated = cb;return vi.fn();@@ -2036,6 +2042,44 @@ describe('makerChatStore text delta batching', () => {]);});+ it.each(['local', 'remote'] as const)('preserves newer queued text when an older item is retracted through %s ingress', (source) => {+ if (source === 'remote') remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ const send = (channel: string, payload: unknown) => {+ if (source === 'remote') onRemotePush?.({ deviceId: 'device-1', channel, payload });+ else if (channel === 'maker:event') onEvent?.(payload);+ else onDbMessageDeleted?.(payload);+ };+ const text = (persistId: string, value: string) => send('maker:event', {+ sessionId: SESSION_ID, persistId,+ event: { type: 'text', source: 'codex', data: { text: value, isFinal: false } },+ });+ text('old-a', 'Withdrawn');+ vi.advanceTimersByTime(32);+ text('new-b', 'Next');+ vi.advanceTimersByTime(32);+ text('new-b', ' pending');+ send('local-db:messages:deleted', { sessionId: SESSION_ID, clientId: 'old-a', clientIds: ['old-a'] });+ vi.advanceTimersByTime(32);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([+ expect.objectContaining({ clientId: 'new-b', content: 'Next pending', isStreaming: true }),+ ]);+ text('new-b', ' tail');+ vi.advanceTimersByTime(32);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages[0].content).toBe('Next pending tail');+ // Legacy deltas without persistId inherit the current stream identity.+ send('maker:event', { sessionId: SESSION_ID,+ event: { type: 'text', data: { text: ' anonymous', isFinal: false } } });+ send('local-db:messages:deleted', { sessionId: SESSION_ID, clientId: 'old-a' });+ vi.advanceTimersByTime(32);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages[0].content).toBe('Next pending tail anonymous');+ // Deleting the actual batch owner must still discard it without resurrection.+ send('maker:event', { sessionId: SESSION_ID,+ event: { type: 'text', data: { text: ' discarded', isFinal: false } } });+ send('local-db:messages:deleted', { sessionId: SESSION_ID, clientId: 'new-b' });+ vi.advanceTimersByTime(32);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toHaveLength(0);+ });+it('calibrates an earlier finalized item in place without sealing a newer stream', () => {onEvent?.({sessionId: SESSION_ID,diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 982b999555..11687f735d 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -12516,7 +12516,11 @@ function removeMessagesByClientIds(// 启动就把它 hydrate 回来(review: codex P1)。缓存是纯优化,清掉即可(下一次成功的// 最新页拉取会重新写上)。invalidateRemoteMessageCache(sessionId);- discardPendingTextDelta(sessionId);+ // An older item can be retracted while the next item is still streaming.+ // Retire only the deleted item's batch; keep unrelated text and its ingress fence.+ const pending = pendingTextDeltaBatches.get(sessionId);+ const pendingClientId = pending?.persistId ?? sessions.get(sessionId)?.streamingClientId;+ if (!pendingClientId || deletedClientIds.has(pendingClientId)) discardPendingTextDelta(sessionId);// 作废删除提交前发起的历史分页,避免旧页响应把已经清除的行重新 merge 回来。if (options.invalidateHistory !== false) invalidateMessageHistoryWindow(sessionId);setState(sessionId, (s) => {