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 queued finals and anonymous stream ownership
xd44b4bd7a5174
diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.tsindex 6d7b4be328..b0f595161c 100644--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts@@ -2735,6 +2735,29 @@ describe('assistant isFinal burst DUP-SKIP(P1:main 对称去重,防重复 isFinaexpect(assistantCreates).toHaveLength(1);});+ it.each(['next-delta', 'tool-result', 'clear', 'owner'] as const)('keeps accepted boundary corrections until clear/owner changes (%s)', async (boundary) => {+ const persistId = onAssistantTextEvent(SESSION, { text: 'Draft', isFinal: false }, null);+ flushAssistantBlock(SESSION, null);+ onInteractionMessage(SESSION, {+ kind: 'ask_user_question', requestId: 'queued-final', questions: [{ question: 'Continue?' }],+ });+ await flushWrites();+ let savedText = 'Draft';+ vi.mocked(updateMessageContent).mockImplementationOnce(async (_sessionId, _clientId, text, _scope, options) => {+ if (options?.isCurrent && !options.isCurrent()) return null;+ if (typeof text !== 'string') throw new Error('Expected assistant text');+ savedText = text;+ return {} as Awaited<ReturnType<typeof updateMessageContent>>;+ });+ expect(onAssistantTextEvent(SESSION, { text: 'Corrected', isFinal: true, isFullText: true }, null)).toBe(persistId);+ if (boundary === 'clear') noteSessionClearBoundary(SESSION, Date.now() + 1000);+ else if (boundary === 'owner') ownerScopeState.current = false;+ else if (boundary === 'tool-result') onToolResultEvent(SESSION, { toolUseIds: ['queued-tool'], summary: 'done' }, null);+ else onAssistantTextEvent(SESSION, { text: 'Next reply', isFinal: false }, null);+ await flushWrites();+ expect(savedText).toBe(boundary === 'clear' || boundary === 'owner' ? 'Draft' : 'Corrected');+ });+it('边界后落过别的消息(tool_use)时同文本快照不复用,仍单独落行', async () => {const persistId = onAssistantTextEvent(SESSION, { text: 'Done.', isFinal: false }, null);flushAssistantBlock(SESSION, null);@@ -2922,6 +2945,30 @@ describe('stale-idle assistant late final identity', () => {expect(broadcastMessageRow).toHaveBeenCalled();});+ it.each(['next-seal', 'clear', 'owner'] as const)('keeps an accepted sealed correction across candidate replacement (%s)', async (boundary) => {+ const meta = { requestId: 'sealed-a', uuid: 'sealed-a' };+ onAssistantTextEvent(SESSION, { text: 'Draft', isFinal: false }, meta);+ sealAssistantBlockForLateFinal(SESSION);+ resetTurnPersistState(SESSION);+ await flushWrites();+ let savedText = 'Draft';+ vi.mocked(updateMessageContent).mockImplementationOnce(async (_sessionId, _clientId, text, _scope, options) => {+ if (options?.isCurrent && !options.isCurrent()) return null;+ if (typeof text !== 'string') throw new Error('Expected assistant text');+ savedText = text;+ return {} as Awaited<ReturnType<typeof updateMessageContent>>;+ });+ onAssistantTextEvent(SESSION, { text: 'Corrected', isFinal: true, isFullText: true }, meta);+ if (boundary === 'clear') noteSessionClearBoundary(SESSION, Date.now() + 1000);+ else if (boundary === 'owner') ownerScopeState.current = false;+ else {+ onAssistantTextEvent(SESSION, { text: 'Next reply', isFinal: false }, { requestId: 'sealed-b', uuid: 'sealed-b' });+ sealAssistantBlockForLateFinal(SESSION);+ }+ await flushWrites();+ expect(savedText).toBe(boundary === 'next-seal' ? 'Corrected' : 'Draft');+ });+it('keeps identical text from a different SDK request as a separate message', async () => {const firstId = onAssistantTextEvent(SESSION,diff --git a/apps/desktop/src/main/messagePersistBroadcaster.ts b/apps/desktop/src/main/messagePersistBroadcaster.tsindex 0f1ad367e9..3402b695a5 100644--- a/apps/desktop/src/main/messagePersistBroadcaster.ts+++ b/apps/desktop/src/main/messagePersistBroadcaster.ts@@ -2298,20 +2298,20 @@ function assembleAssistantTextEvent() {const contentChanged = visible !== lateFinalCandidate.text;if (contentChanged) {- const isCandidateCurrent = () =>- sealedAssistantLateFinalBySession.get(sessionId) === lateFinalCandidate;+ const clearBoundary = clearBoundaryBySession.get(sessionId);+ const isCurrentBoundary = () => clearBoundaryBySession.get(sessionId) === clearBoundary;enqueueWrite(`assistant_late_final:${sessionId}:${lateFinalCandidate.persistId}`,async (ownerScope) => {- if (!isCandidateCurrent()) return;+ if (!isCurrentBoundary()) return;const updated = await updateDbMessageContent(sessionId,lateFinalCandidate.persistId,visible,undefined,- { isCurrent: () => isCandidateCurrent() && isOwnerScopeCurrent(ownerScope) },+ { isCurrent: () => isCurrentBoundary() && isOwnerScopeCurrent(ownerScope) },);- if (updated && isCandidateCurrent()) {+ if (updated && isCurrentBoundary() && isOwnerScopeCurrent(ownerScope)) {lateFinalCandidate.text = visible;broadcastMessageRow(sessionId, updated, ownerScope);}@@ -2373,6 +2373,10 @@ function assembleAssistantTextEvent(// delta 未消费 / 流式纠错),此时用全文更新既有行,而不是要求逐字相等后另起// 一行(否则仍是"部分文本 + 提问卡 + 完整文本"两行)。if (isFullText && boundaryFlushed.text !== visible) {+ // Eligibility ends at the next block, but an already accepted correction+ // still owns its durable row. Only clear/account changes invalidate it.+ const clearBoundary = clearBoundaryBySession.get(sessionId);+ const isCurrentBoundary = () => clearBoundaryBySession.get(sessionId) === clearBoundary;enqueueWrite(`boundary_flushed_content:${sessionId}:${boundaryFlushed.persistId}`,async (ownerScope) => {@@ -2381,7 +2385,7 @@ function assembleAssistantTextEvent(boundaryFlushed.persistId,visible,undefined,- { isCurrent: () => lastBoundaryFlushedAssistantBySession.get(sessionId) === boundaryFlushed && isOwnerScopeCurrent(ownerScope) },+ { isCurrent: () => isCurrentBoundary() && isOwnerScopeCurrent(ownerScope) },);if (updated) {// 缓存已落库的全文:重复投递同一份快照时不再重复 UPDATE。diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.tsindex 5ab13916a4..5fded43c54 100644--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts@@ -888,14 +888,16 @@ describe('remoteSessionStore', () => {} finally { vi.useRealTimers(); }});- it.each([false, true])('calibrates a late final by identity without taking over a newer stream (newer=%s)', (newer) => {+ it.each([false, true, 'anonymous', 'anonymous-same-prefix'] as const)('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',}]);+ const anonymous = typeof newer === 'string';+ const nextText = newer === 'anonymous-same-prefix' ? 'Correct' : 'Next';if (newer) {- pushMakerText('s1', 'item-b', 'Next', false);+ pushMakerText('s1', anonymous ? undefined : 'item-b', nextText, false);vi.runOnlyPendingTimers();}remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {@@ -905,16 +907,45 @@ describe('remoteSessionStore', () => {});expect(remoteSessionStore.getMessages('s1').find((row) => row.clientId === 'item-a')?.content).toBe('Corrected');if (newer) {+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:created', {+ sessionId: 's1', message: { ...message('host-a', 's1'), clientId: 'item-a', content: 'Corrected' },+ });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').find((row) => anonymous ? row.clientId?.startsWith('mobile-stream-') : row.clientId === 'item-b'))+ .toMatchObject({ content: `${nextText} tail`, agentMeta: { isStreaming: true } });}expect(remoteSessionStore.getMessages('s1')).toHaveLength(newer ? 2 : 1);} finally { vi.useRealTimers(); }});- it('migrates a short anonymous stream when its DB row arrives before the identified final', () => {+ it.each(['db-row', 'full-final'] as const)('keeps an anonymous stream when an older row reappears outside the current window (%s)', (arrival) => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setMessages('s1', [{ ...message('host-a', 's1'), clientId: 'item-a', content: 'Old draft' }]);+ const prefix = 'A shared introductory sentence';+ pushMakerText('s1', undefined, prefix, false);+ vi.runOnlyPendingTimers();+ const newer = remoteSessionStore.getMessages('s1').find((row) => row.clientId?.startsWith('mobile-stream-'))!;+ remoteSessionStore.setMessages('s1', [newer]);+ if (arrival === 'full-final') {+ remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {+ sessionId: 's1', persistId: 'item-a', event: {+ type: 'text', data: { text: `${prefix} from the older reply`, isFinal: true, isFullText: true },+ },+ });+ }+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:created', {+ sessionId: 's1', message: { ...message('host-a', 's1'), clientId: 'item-a', content: `${prefix} from the older reply` },+ });+ pushMakerText('s1', undefined, ' tail', false);+ vi.runOnlyPendingTimers();+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(2);+ expect(remoteSessionStore.getMessages('s1').find((row) => row.clientId === newer.clientId)?.content).toBe(`${prefix} tail`);+ } finally { vi.useRealTimers(); }+ });++ it.each(['Sure, checked', 'Corrected'])('migrates a short anonymous stream when its DB row precedes the identified final (%s)', (finalText) => {vi.useFakeTimers();try {pushMakerText('s1', undefined, 'Sure', false);@@ -925,14 +956,14 @@ describe('remoteSessionStore', () => {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 },+ type: 'text', data: { text: finalText, 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',+ id: 'host-a', clientId: 'item-a', content: `${finalText} tail`,})]);} finally { vi.useRealTimers(); }});diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex c70d80b167..65b508be31 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -625,6 +625,9 @@ const sessionTaskUpdates = new Map<string, ReadonlyMap<string, AgentTaskUpdate>>// Keep one temporary assistant row per session and reconcile it with the persisted row by// clientId/persistId when the database push arrives.const streamingAssistantClientIds = new Map<string, string>();+// A final for an item already present when an anonymous stream began cannot+// claim that newer stream. Keep the observation boundary until its id resolves.+const generatedStreamPriorIdentities = new Map<string, ReadonlySet<string>>();// The same persisted streaming identity can be replayed by a stale transport after// re-link. Track the transport currently assembling that identity so a device switch// replaces the stale live text instead of concatenating two transports into one row.@@ -697,6 +700,7 @@ function forgetStreamingAssistantDeviceId(sessionId: string, clientId: string):}function clearStreamingAssistantPointer(sessionId: string): boolean {+ generatedStreamPriorIdentities.delete(sessionId);return streamingAssistantClientIds.delete(sessionId);}@@ -1262,7 +1266,7 @@ function discardTransportOwnedPendingSessionState(}const streamingClientId = streamingAssistantClientIds.get(sessionId);if (streamingClientId && pendingAnchorIds.has(streamingClientId)) {- streamingAssistantClientIds.delete(sessionId);+ clearStreamingAssistantPointer(sessionId);}for (const id of pendingAnchorIds) forgetStreamingAssistantDeviceId(sessionId, id);if (pendingAnchors) {@@ -2435,7 +2439,7 @@ function reanchorPendingLiveAssistantRows(function retireGeneratedStreamingFallback(sessionId: string): void {const current = streamingAssistantClientIds.get(sessionId);- if (isGeneratedStreamingClientId(current)) streamingAssistantClientIds.delete(sessionId);+ if (isGeneratedStreamingClientId(current)) clearStreamingAssistantPointer(sessionId);forgetGeneratedPendingLiveAssistantClientIds(sessionId);}@@ -2495,6 +2499,7 @@ interface StreamingClientIdResolution {}function migrateGeneratedStreamingClientId(sessionId: string, generatedClientId: string, persistId: string): boolean {+ generatedStreamPriorIdentities.delete(sessionId);streamingAssistantClientIds.set(sessionId, persistId);const hadPendingLiveId = pendingLiveAssistantClientIds.get(sessionId)?.has(generatedClientId) === true;@@ -2553,12 +2558,16 @@ function streamingClientIdFor(sessionId: string, persistId: string | undefined):changed: migrateGeneratedStreamingClientId(sessionId, existing, normalizedPersistId),};}+ generatedStreamPriorIdentities.delete(sessionId);streamingAssistantClientIds.set(sessionId, normalizedPersistId);return { clientId: normalizedPersistId, changed: false };}const existing = streamingAssistantClientIds.get(sessionId);if (existing) return { clientId: existing, changed: false };const generated = `mobile-stream-${++streamingFallbackSequence}`;+ generatedStreamPriorIdentities.set(sessionId, new Set(+ (messages.get(sessionId) ?? []).flatMap((row) => [row.id, row.clientId].filter((id): id is string => Boolean(id))),+ ));streamingAssistantClientIds.set(sessionId, generated);return { clientId: generated, changed: false };}@@ -2570,6 +2579,8 @@ function upsertMessage(/** Caller already resolved this exact identity in the current message array. */knownIndex?: number;retirePendingAssistantIdentityOnEqual?: boolean;+ /** An older final with no proven link must not retire an anonymous new stream. */+ preserveGeneratedStreamingFallback?: boolean;/** A streaming text replacement changes row content but not list structure or identities. */preserveStructureOnReplace?: boolean;/** Streaming replacement preserves the already sorted message order. */@@ -2577,6 +2588,10 @@ function upsertMessage(} = {},): boolean {const existing = messages.get(sessionId) ?? [];+ const priorIdentities = generatedStreamPriorIdentities.get(sessionId);+ const preservesGeneratedStream = options.preserveGeneratedStreamingFallback === true+ || priorIdentities?.has(message.id) === true+ || (message.clientId ? priorIdentities?.has(message.clientId) === true : false);const candidateIndex = options.knownIndex ?? -1;const index = candidateIndex >= 0&& candidateIndex < existing.length@@ -2588,6 +2603,7 @@ function upsertMessage(fallbackIndex = findPendingGeneratedStreamingFallbackIndex(sessionId, existing);if (fallbackIndex >= 0+ && !preservesGeneratedStream&& generatedFallbackMatchesPersistedMessage(existing[fallbackIndex], message)) {// A producer without persistId creates a temporary mobile-stream-* row. The@@ -2604,7 +2620,7 @@ function upsertMessage(if (index < 0) {messages.set(sessionId, normalizeMessages([...existing, message]));applyMessageWriteRetention(sessionId);- if (isPersistedAssistantMessage(message) && fallbackIndex < 0) {+ if (isPersistedAssistantMessage(message) && fallbackIndex < 0 && !preservesGeneratedStream) {retireGeneratedStreamingFallback(sessionId);}bumpMessageVersion(sessionId);@@ -2631,7 +2647,7 @@ function upsertMessage(message.id,message.clientId,);- if (isPersistedAssistantMessage(message)) retireGeneratedStreamingFallback(sessionId);+ if (isPersistedAssistantMessage(message) && !preservesGeneratedStream) retireGeneratedStreamingFallback(sessionId);return hadPendingIdentity;}const next = existing.slice();@@ -2655,7 +2671,7 @@ function upsertMessage(message.id,message.clientId,);- if (isPersistedAssistantMessage(message)) retireGeneratedStreamingFallback(sessionId);+ if (isPersistedAssistantMessage(message) && !preservesGeneratedStream) retireGeneratedStreamingFallback(sessionId);}bumpMessageVersion(sessionId);return true;@@ -2737,17 +2753,24 @@ function mergeRemoteTextEvent(const normalizedPersistId = persistId?.trim();// 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 priorIdentities = generatedStreamPriorIdentities.get(sessionId);const finalReusesExistingItem = isFinal && data?.isFullText === true && normalizedPersistId- && currentMessages.some((row) => row.role === 'assistant'- && (row.clientId === normalizedPersistId || row.id === normalizedPersistId));+ && (priorIdentities?.has(normalizedPersistId) === true+ || currentMessages.some((row) => row.role === 'assistant'+ && (row.clientId === normalizedPersistId || row.id === normalizedPersistId)));const itemBoundaryClientId = !finalReusesExistingItem && normalizedPersistId&& previousStreamingClientId&& !isGeneratedStreamingClientId(previousStreamingClientId)&& previousStreamingClientId !== normalizedPersistId? previousStreamingClientId: undefined;+ const generatedStream = finalReusesExistingItem && isGeneratedStreamingClientId(previousStreamingClientId)+ ? currentMessages.find((row) => row.id === previousStreamingClientId || row.clientId === previousStreamingClientId)+ : undefined;+ const finalCanClaimGeneratedStream = Boolean(normalizedPersistId && generatedStream+ && priorIdentities && !priorIdentities.has(normalizedPersistId));const clientIdResolution = finalReusesExistingItem && normalizedPersistId- && (!previousStreamingClientId || !isGeneratedStreamingClientId(previousStreamingClientId))+ && !finalCanClaimGeneratedStream? { clientId: normalizedPersistId, changed: false }: streamingClientIdFor(sessionId, persistId);const { clientId } = clientIdResolution;@@ -2909,6 +2932,7 @@ function mergeRemoteTextEvent(),}, {knownIndex: matchedExistingIndex,+ preserveGeneratedStreamingFallback: Boolean(finalReusesExistingItem && generatedStream && !finalCanClaimGeneratedStream),preserveOrderOnReplace: !changesCreatedAt,preserveStructureOnReplace: !isFinal && existing !== undefined && !changesCreatedAt,});@@ -5429,6 +5453,7 @@ export const remoteSessionStore = {sessionLiveStreamAcked.clear();sessionTaskUpdates.clear();streamingAssistantClientIds.clear();+ generatedStreamPriorIdentities.clear();streamingAssistantDeviceIds.clear();pendingLiveAssistantClientIds.clear();pendingHostAnchorLiveAssistantClientIds.clear();diff --git a/scripts/test-hygiene-baseline.json b/scripts/test-hygiene-baseline.jsonindex d99ae8ae02..ecac9d5cf0 100644--- a/scripts/test-hygiene-baseline.json+++ b/scripts/test-hygiene-baseline.json@@ -120,7 +120,7 @@"sourceReads": 1},"apps/desktop/src/main/__tests__/sessionTaskSummary.test.ts": {- "sourceReads": 4+ "sourceReads": 2},"apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts": {"sourceReads": 2