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): reuse message identity for late final snapshots

xd9ef5d3d37c5c
diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
index 38219a7746..6ed4850398 100644
--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
@@ -2976,6 +2976,132 @@ describe('stale-idle assistant late final identity', () => {
});
describe('streamed assistant final calibration', () => {
+ it.each(['tool_use', 'tool_result'])('reuses a Codex item after an intervening %s', async (boundary) => {
+ const persistId = onAssistantTextEvent(SESSION,
+ { text: 'Checking branch', agentMessageId: 'msg-a' }, null);
+ flushAssistantBlock(SESSION);
+ onToolUseEvent(SESSION, { toolUseId: 'cmd-a', toolName: 'exec', input: {} }, null);
+ if (boundary === 'tool_result') {
+ onToolResultEvent(SESSION, { toolUseIds: ['cmd-a'], summary: 'main' }, null);
+ }
+ const final = { text: 'Checking branch', isFinal: true, isFullText: true, agentMessageId: 'msg-a' };
+ expect(onAssistantTextEvent(SESSION, final, null)).toBe(persistId);
+ expect(onAssistantTextEvent(SESSION, final, null)).toBe(persistId);
+ await flushWrites();
+ expect(vi.mocked(createMessage).mock.calls.filter(([, message]) => message.role === 'assistant')).toHaveLength(1);
+ });
+
+ 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);
+ flushAssistantBlock(SESSION);
+ onToolUseEvent(SESSION, { toolUseId: 'cmd-a', toolName: 'exec', input: {} }, null);
+ const nextId = onAssistantTextEvent(SESSION,
+ { text: 'Next step', agentMessageId: 'msg-b' }, null);
+ const before = getSessionTextSnapshot(SESSION);
+ expect(onAssistantTextEvent(SESSION,
+ { text: 'Corrected', isFinal: true, isFullText: true, agentMessageId: 'msg-a' },
+ { model: 'test-model' })).toBe(firstId);
+ expect(getSessionTextSnapshot(SESSION)).toEqual(before);
+ await flushWrites();
+ expect(updateMessageContent).toHaveBeenCalledWith(SESSION, firstId, 'Corrected');
+ expect(patchMessageAgentMetaWithResult).toHaveBeenCalledWith(SESSION, firstId, { model: 'test-model' });
+ expect(broadcastMessageRow).toHaveBeenCalled();
+ expect(vi.mocked(createMessage).mock.calls.filter(([, message]) => message.role === 'assistant')).toHaveLength(1);
+ flushAssistantBlock(SESSION);
+ await flushWrites();
+ expect(vi.mocked(createMessage).mock.calls.filter(([, message]) => message.role === 'assistant')
+ .map(([, message]) => message.clientId)).toEqual([firstId, nextId]);
+ });
+
+ it('persists a final snapshot when the preceding empty block was discarded', async () => {
+ onAssistantTextEvent(SESSION, { text: '', agentMessageId: 'msg-empty' }, null);
+ flushAssistantBlock(SESSION);
+ onToolUseEvent(SESSION, { toolUseId: 'cmd-a', toolName: 'exec', input: {} }, null);
+ const persistId = onAssistantTextEvent(SESSION,
+ { text: 'Recovered text', isFinal: true, isFullText: true, agentMessageId: 'msg-empty' }, null);
+ await flushWrites();
+ expect(createMessage).toHaveBeenCalledWith(SESSION,
+ expect.objectContaining({ clientId: persistId, role: 'assistant', content: 'Recovered text' }), broadcastGuard());
+ });
+
+ it('does not publish a queued old-item correction after the transcript is cleared', async () => {
+ const persistId = onAssistantTextEvent(SESSION,
+ { text: 'Before clear', agentMessageId: 'msg-a' }, null);
+ flushAssistantBlock(SESSION);
+ await flushWrites();
+ onAssistantTextEvent(SESSION,
+ { text: 'Late correction', isFinal: true, isFullText: true, agentMessageId: 'msg-a' }, null);
+ noteSessionClearBoundary(SESSION, Date.now() + 1000);
+ await flushWrites();
+ expect(updateMessageContent).not.toHaveBeenCalledWith(SESSION, persistId, 'Late correction');
+ expect(broadcastMessageRow).not.toHaveBeenCalled();
+ });
+
+ it.each(['clear', 'owner'])('stops an in-flight old-item correction when %s changes', async (boundary) => {
+ onAssistantTextEvent(SESSION, { text: 'Before boundary', agentMessageId: 'msg-a' }, null);
+ flushAssistantBlock(SESSION);
+ await flushWrites();
+ vi.mocked(updateMessageContent).mockImplementationOnce(async () => {
+ if (boundary === 'clear') noteSessionClearBoundary(SESSION, Date.now() + 1000);
+ else ownerScopeState.current = false;
+ return {} as never;
+ });
+ onAssistantTextEvent(SESSION,
+ { text: 'Late correction', isFinal: true, isFullText: true, agentMessageId: 'msg-a' },
+ { model: 'test-model' });
+ await flushWrites();
+ expect(broadcastMessageRow).not.toHaveBeenCalled();
+ expect(patchMessageAgentMetaWithResult).not.toHaveBeenCalled();
+ });
+
+ it('keeps the newer item as the completion target after an older final snapshot', async () => {
+ onAssistantTextEvent(SESSION, { text: 'Opening', agentMessageId: 'msg-a' }, null);
+ flushAssistantBlock(SESSION);
+ const nextId = onAssistantTextEvent(SESSION,
+ { text: 'Done', isFinal: true, isFullText: true, agentMessageId: 'msg-b' }, null);
+ onAssistantTextEvent(SESSION,
+ { text: 'Opening corrected', isFinal: true, isFullText: true, agentMessageId: 'msg-a' }, null);
+ expect(consumeLastTopLevelAssistantPersistId(SESSION)).toBe(nextId);
+ await flushWrites();
+ });
+
+ it('keeps equal text from different items separate across a tool boundary', async () => {
+ const firstId = onAssistantTextEvent(SESSION,
+ { text: 'Checking', agentMessageId: 'msg-a' }, null);
+ flushAssistantBlock(SESSION);
+ onToolUseEvent(SESSION, { toolUseId: 'cmd-a', toolName: 'exec', input: {} }, null);
+ const nextId = onAssistantTextEvent(SESSION,
+ { text: 'Checking', isFinal: true, isFullText: true, agentMessageId: 'msg-b' }, null);
+ expect(nextId).not.toBe(firstId);
+ await flushWrites();
+ expect(vi.mocked(createMessage).mock.calls.filter(([, message]) => message.role === 'assistant')).toHaveLength(2);
+ });
+
+ it('does not borrow foreground item identity for background text', async () => {
+ const firstId = onAssistantTextEvent(SESSION,
+ { text: 'Foreground', agentMessageId: 'msg-a' }, null);
+ flushAssistantBlock(SESSION);
+ onToolUseEvent(SESSION, { toolUseId: 'cmd-a', toolName: 'exec', input: {} }, null);
+ const backgroundId = onAssistantTextEvent(SESSION,
+ { text: 'Background', isFinal: true, isFullText: true, agentMessageId: 'msg-a' }, null, 'background');
+ expect(backgroundId).not.toBe(firstId);
+ await flushWrites();
+ expect(updateMessageContent).not.toHaveBeenCalled();
+ });
+
+ it.each(['turn', 'clear', 'session'])('does not reuse an item across a %s boundary', async (boundary) => {
+ const firstId = onAssistantTextEvent(SESSION,
+ { text: 'Ready', isFinal: true, isFullText: true, agentMessageId: 'msg-a' }, null);
+ if (boundary === 'turn') resetTurnPersistState(SESSION);
+ if (boundary === 'clear') noteSessionClearBoundary(SESSION, new Date(Date.now() + 1000).toISOString());
+ if (boundary === 'session') clearSessionPersistState(SESSION);
+ const nextId = onAssistantTextEvent(SESSION,
+ { text: 'New turn', isFinal: true, isFullText: true, agentMessageId: 'msg-a' }, null);
+ expect(nextId).not.toBe(firstId);
+ await flushWrites();
+ });
+
it('persists commentary and final_answer as separate rows when Codex item ids change', async () => {
const commentaryId = onAssistantTextEvent(
SESSION,
diff --git a/apps/desktop/src/main/messagePersistBroadcaster.ts b/apps/desktop/src/main/messagePersistBroadcaster.ts
index 4379a2b940..7827207e9f 100644
--- a/apps/desktop/src/main/messagePersistBroadcaster.ts
+++ b/apps/desktop/src/main/messagePersistBroadcaster.ts
@@ -2233,6 +2233,32 @@ function assembleAssistantTextEvent(
: undefined;
const activeBlock = assistantBlocks.get(sessionId);
+ const linkedPersistId = agentMessageId && turnScope !== 'background'
+ ? assistantItemPersistIds.get(sessionId)?.get(agentMessageId)
+ : undefined;
+ // Codex can finish an item after tool events already flushed its text, or
+ // after a newer item started streaming. Calibrate that exact durable row
+ // before the item-boundary logic can flush the newer stream. Text equality
+ // cannot identify an item: separate messages may legitimately say the same thing.
+ if (isFinal && isFullText && linkedPersistId && activeBlock?.persistId !== linkedPersistId) {
+ const visible = stripInternalWebCitations(rawText);
+ const clearBoundary = clearBoundaryBySession.get(sessionId);
+ const isCurrentBoundary = () => clearBoundaryBySession.get(sessionId) === clearBoundary;
+ enqueueWrite(`assistant_item_final:${sessionId}:${linkedPersistId}`, async (ownerScope) => {
+ if (!isCurrentBoundary()) return;
+ const updated = await updateDbMessageContent(sessionId, linkedPersistId, visible);
+ if (!isCurrentBoundary() || !isOwnerScopeCurrent(ownerScope)) return;
+ if (updated) broadcastMessageRow(sessionId, updated, ownerScope);
+ if (agentMeta) {
+ const patched = await patchMessageAgentMetaWithResult(sessionId, linkedPersistId, { ...agentMeta });
+ if (patched && isCurrentBoundary()) {
+ await broadcastMessageAgentMetaUpdate(sessionId, linkedPersistId, ownerScope);
+ }
+ }
+ });
+ // Preserve the newer stream and the turn's existing completion/cost target.
+ return linkedPersistId;
+ }
if (
activeBlock?.agentMessageId &&
agentMessageId &&
@@ -2445,7 +2471,15 @@ function flushAssistantBlockInternal(
if (!block) return undefined;
assistantBlocks.delete(sessionId);
const visible = stripInternalWebCitations(block.text);
- if (!visible) return undefined;
+ if (!visible) {
+ // No row was queued for this block, so a later full snapshot must create
+ // one rather than treating the discarded item as an already durable row.
+ if (block.agentMessageId) {
+ const links = assistantItemPersistIds.get(sessionId);
+ if (links?.get(block.agentMessageId) === block.persistId) links.delete(block.agentMessageId);
+ }
+ return undefined;
+ }
// 三级兜底,对齐 renderer 老逻辑:本 block 自带 meta → 边界事件 meta(tool_use/done
// 同属或携带这条 assistant 的 meta)→ 会话最近一次非空 meta(interaction 边界靠这级)。
const meta = block.agentMeta ?? agentMetaFallback ?? lastAgentMetaBySession.get(sessionId) ?? null;
diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
index 9ae066bf05..2d4144eb6d 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -871,6 +871,32 @@ describe('remoteSessionStore', () => {
} finally { vi.useRealTimers(); }
});
+ it.each([false, true])('calibrates a late final by identity without taking over a newer stream (newer=%s)', (newer) => {
+ vi.useFakeTimers();
+ try {
+ remoteSessionStore.setMessages('s1', [{
+ ...message('host-a', 's1'), clientId: 'item-a', content: 'Incorrect long draft',
+ }]);
+ if (newer) {
+ pushMakerText('s1', 'item-b', 'Next', false);
+ vi.runOnlyPendingTimers();
+ }
+ remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {
+ sessionId: 's1', persistId: 'item-a', event: {
+ type: 'text', data: { text: 'Corrected', isFinal: true, isFullText: true },
+ },
+ });
+ expect(remoteSessionStore.getMessages('s1').find((row) => row.clientId === 'item-a')?.content).toBe('Corrected');
+ if (newer) {
+ pushMakerText('s1', undefined, ' tail', false);
+ vi.runOnlyPendingTimers();
+ expect(remoteSessionStore.getMessages('s1').find((row) => row.clientId === 'item-b'))
+ .toMatchObject({ content: 'Next tail', agentMeta: { isStreaming: true } });
+ }
+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(newer ? 2 : 1);
+ } 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 5db904ebb1..8804522b82 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -2735,13 +2735,20 @@ function mergeRemoteTextEvent(
const previousStreamingClientId = streamingAssistantClientIds.get(sessionId);
const normalizedPersistId = persistId?.trim();
- const itemBoundaryClientId = normalizedPersistId
+ // A completed older item may deliver its full text after a newer stream has
+ // started. Its exact row owns this correction, not the current stream pointer.
+ const finalReusesExistingItem = isFinal && data?.isFullText === true && normalizedPersistId
+ && currentMessages.some((row) => row.role === 'assistant'
+ && (row.clientId === normalizedPersistId || row.id === normalizedPersistId));
+ const itemBoundaryClientId = !finalReusesExistingItem && normalizedPersistId
&& previousStreamingClientId
&& !isGeneratedStreamingClientId(previousStreamingClientId)
&& previousStreamingClientId !== normalizedPersistId
? previousStreamingClientId
: undefined;
- const clientIdResolution = streamingClientIdFor(sessionId, persistId);
+ const clientIdResolution = finalReusesExistingItem && normalizedPersistId
+ ? { clientId: normalizedPersistId, changed: false }
+ : streamingClientIdFor(sessionId, persistId);
const { clientId } = clientIdResolution;
const previousStreamingDeviceId = streamingAssistantDeviceId(sessionId, clientId);
const currentAfterClientIdResolution = messages.get(sessionId) ?? [];
@@ -2854,7 +2861,9 @@ function mergeRemoteTextEvent(
const nextText = isFinal
? (finalTextWasTruncated && existing
? currentText
- : existing && currentText
+ : data?.isFullText === true
+ ? text
+ : existing && currentText
? (text.startsWith(currentText)
? text
: currentText.startsWith(text)