fix(chat): prevent duplicate renderer requests and thinking messages (#870)
Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: Haze <hazeone@users.noreply.github.com>
This commit is contained in:
@@ -41,11 +41,40 @@ vi.mock('@/stores/chat/helpers', () => ({
|
||||
clearHistoryPoll: (...args: unknown[]) => clearHistoryPoll(...args),
|
||||
enrichWithCachedImages: (...args: unknown[]) => enrichWithCachedImages(...args),
|
||||
enrichWithToolResultFiles: (...args: unknown[]) => enrichWithToolResultFiles(...args),
|
||||
getLatestOptimisticUserMessage: (messages: Array<{ role: string; timestamp?: number }>, userTimestampMs: number) =>
|
||||
[...messages].reverse().find(
|
||||
(message) => message.role === 'user'
|
||||
&& (!message.timestamp || Math.abs(toMs(message.timestamp) - userTimestampMs) < 5000),
|
||||
),
|
||||
getMessageText: (...args: unknown[]) => getMessageText(...args),
|
||||
hasNonToolAssistantContent: (...args: unknown[]) => hasNonToolAssistantContent(...args),
|
||||
isInternalMessage: (...args: unknown[]) => isInternalMessage(...args),
|
||||
isToolResultRole: (...args: unknown[]) => isToolResultRole(...args),
|
||||
loadMissingPreviews: (...args: unknown[]) => loadMissingPreviews(...args),
|
||||
matchesOptimisticUserMessage: (
|
||||
candidate: { role: string; timestamp?: number; content?: unknown; _attachedFiles?: Array<{ filePath?: string; fileName?: string; mimeType?: string; fileSize?: number }> },
|
||||
optimistic: { role: string; timestamp?: number; content?: unknown; _attachedFiles?: Array<{ filePath?: string; fileName?: string; mimeType?: string; fileSize?: number }> },
|
||||
optimisticTimestampMs: number,
|
||||
) => {
|
||||
if (candidate.role !== 'user') return false;
|
||||
const normalizeText = (content: unknown) => (typeof content === 'string' ? content : '')
|
||||
.replace(/^\[(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s+\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}\s+[^\]]+\]\s*/i, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
const candidateText = normalizeText(candidate.content);
|
||||
const optimisticText = normalizeText(optimistic.content);
|
||||
const candidateAttachments = (candidate._attachedFiles || []).map((file) => file.filePath || `${file.fileName}|${file.mimeType}|${file.fileSize}`).sort().join('::');
|
||||
const optimisticAttachments = (optimistic._attachedFiles || []).map((file) => file.filePath || `${file.fileName}|${file.mimeType}|${file.fileSize}`).sort().join('::');
|
||||
const hasCandidateTimestamp = candidate.timestamp != null;
|
||||
const timestampMatches = hasCandidateTimestamp
|
||||
? Math.abs(toMs(candidate.timestamp as number) - optimisticTimestampMs) < 5000
|
||||
: false;
|
||||
|
||||
if (candidateText && optimisticText && candidateText === optimisticText && candidateAttachments === optimisticAttachments) return true;
|
||||
if (candidateText && optimisticText && candidateText === optimisticText && (!hasCandidateTimestamp || timestampMatches)) return true;
|
||||
if (candidateAttachments && optimisticAttachments && candidateAttachments === optimisticAttachments && (!hasCandidateTimestamp || timestampMatches)) return true;
|
||||
return false;
|
||||
},
|
||||
toMs: (...args: unknown[]) => toMs(...args as Parameters<typeof toMs>),
|
||||
}));
|
||||
|
||||
@@ -527,4 +556,45 @@ describe('chat history actions', () => {
|
||||
]);
|
||||
expect(h.read().messages[0]?._attachedFiles?.[0]?.preview).toBe('data:image/png;base64,abc');
|
||||
});
|
||||
|
||||
it('does not append an optimistic duplicate when history already includes the user message without timestamp', async () => {
|
||||
const { createHistoryActions } = await import('@/stores/chat/history-actions');
|
||||
const h = makeHarness({
|
||||
currentSessionKey: 'agent:main:main',
|
||||
sending: true,
|
||||
lastUserMessageAt: 1_773_281_732_000,
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: '[Fri 2026-03-13 10:00 GMT+8] Open browser, search for tech news, and take a screenshot',
|
||||
timestamp: 1_773_281_732,
|
||||
},
|
||||
],
|
||||
});
|
||||
const actions = createHistoryActions(h.set as never, h.get as never);
|
||||
|
||||
invokeIpcMock.mockResolvedValueOnce({
|
||||
success: true,
|
||||
result: {
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: 'Open browser, search for tech news, and take a screenshot',
|
||||
},
|
||||
{
|
||||
role: 'assistant',
|
||||
content: 'Processing',
|
||||
timestamp: 1_773_281_733,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
await actions.loadHistory(true);
|
||||
|
||||
expect(h.read().messages.map((message) => message.content)).toEqual([
|
||||
'Open browser, search for tech news, and take a screenshot',
|
||||
'Processing',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -20,7 +20,9 @@ const makeAttachedFile = vi.fn((ref: { filePath: string; mimeType: string }, sou
|
||||
filePath: ref.filePath,
|
||||
source,
|
||||
}));
|
||||
const normalizeStreamingMessage = vi.fn((message: unknown) => message);
|
||||
const setErrorRecoveryTimer = vi.fn();
|
||||
const snapshotStreamingAssistantMessage = vi.fn((currentStream: unknown) => currentStream ? [currentStream] : []);
|
||||
const upsertToolStatuses = vi.fn((_current, updates) => updates);
|
||||
|
||||
vi.mock('@/stores/chat/helpers', () => ({
|
||||
@@ -37,7 +39,9 @@ vi.mock('@/stores/chat/helpers', () => ({
|
||||
isToolOnlyMessage: (...args: unknown[]) => isToolOnlyMessage(...args),
|
||||
isToolResultRole: (...args: unknown[]) => isToolResultRole(...args),
|
||||
makeAttachedFile: (...args: unknown[]) => makeAttachedFile(...args),
|
||||
normalizeStreamingMessage: (...args: unknown[]) => normalizeStreamingMessage(...args),
|
||||
setErrorRecoveryTimer: (...args: unknown[]) => setErrorRecoveryTimer(...args),
|
||||
snapshotStreamingAssistantMessage: (...args: unknown[]) => snapshotStreamingAssistantMessage(...args),
|
||||
upsertToolStatuses: (...args: unknown[]) => upsertToolStatuses(...args),
|
||||
}));
|
||||
|
||||
@@ -84,6 +88,8 @@ describe('chat runtime event handlers', () => {
|
||||
vi.resetAllMocks();
|
||||
hasErrorRecoveryTimer.mockReturnValue(false);
|
||||
collectToolUpdates.mockReturnValue([]);
|
||||
normalizeStreamingMessage.mockImplementation((message: unknown) => message);
|
||||
snapshotStreamingAssistantMessage.mockImplementation((currentStream: unknown) => currentStream ? [currentStream as Record<string, unknown>] : []);
|
||||
upsertToolStatuses.mockImplementation((_current, updates) => updates);
|
||||
});
|
||||
|
||||
@@ -228,6 +234,100 @@ describe('chat runtime event handlers', () => {
|
||||
expect(h.read().streamingMessage).toEqual(incoming);
|
||||
});
|
||||
|
||||
it('normalizes cumulative text and thinking blocks while streaming', async () => {
|
||||
const { handleRuntimeEventState } = await import('@/stores/chat/runtime-event-handlers');
|
||||
const h = makeHarness({ streamingMessage: null });
|
||||
normalizeStreamingMessage.mockReturnValue({
|
||||
role: 'assistant',
|
||||
content: [
|
||||
{ type: 'thinking', thinking: 'thinking 1 2 3' },
|
||||
{ type: 'text', text: '1 2 3' },
|
||||
],
|
||||
});
|
||||
|
||||
handleRuntimeEventState(h.set as never, h.get as never, {
|
||||
message: {
|
||||
role: 'assistant',
|
||||
content: [
|
||||
{ type: 'thinking', thinking: 'thinking 1' },
|
||||
{ type: 'thinking', thinking: 'thinking 1 2' },
|
||||
{ type: 'thinking', thinking: 'thinking 1 2 3' },
|
||||
{ type: 'text', text: '1' },
|
||||
{ type: 'text', text: '1 2' },
|
||||
{ type: 'text', text: '1 2 3' },
|
||||
],
|
||||
},
|
||||
}, 'delta', 'run-stream');
|
||||
|
||||
expect(h.read().streamingMessage).toEqual({
|
||||
role: 'assistant',
|
||||
content: [
|
||||
{ type: 'thinking', thinking: 'thinking 1 2 3' },
|
||||
{ type: 'text', text: '1 2 3' },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('snapshots normalized streaming content when tool results arrive', async () => {
|
||||
const { handleRuntimeEventState } = await import('@/stores/chat/runtime-event-handlers');
|
||||
normalizeStreamingMessage.mockImplementation((message: unknown) => {
|
||||
const msg = message as { role: string; id: string; content: unknown[] };
|
||||
return {
|
||||
...msg,
|
||||
content: [
|
||||
{ type: 'thinking', thinking: 'thinking 1 2 3' },
|
||||
{ type: 'tool_use', id: 'call-1', name: 'read', input: { filePath: '/tmp/demo.md' } },
|
||||
{ type: 'text', text: '1 2 3' },
|
||||
],
|
||||
};
|
||||
});
|
||||
snapshotStreamingAssistantMessage.mockImplementation((currentStream: unknown) => {
|
||||
const msg = currentStream as { role: string; id: string; content: unknown[] };
|
||||
return [{
|
||||
...msg,
|
||||
content: [
|
||||
{ type: 'thinking', thinking: 'thinking 1 2 3' },
|
||||
{ type: 'tool_use', id: 'call-1', name: 'read', input: { filePath: '/tmp/demo.md' } },
|
||||
{ type: 'text', text: '1 2 3' },
|
||||
],
|
||||
}];
|
||||
});
|
||||
const h = makeHarness({
|
||||
streamingMessage: {
|
||||
role: 'assistant',
|
||||
id: 'streaming-assistant',
|
||||
content: [
|
||||
{ type: 'thinking', thinking: 'thinking 1' },
|
||||
{ type: 'thinking', thinking: 'thinking 1 2 3' },
|
||||
{ type: 'tool_use', id: 'call-1', name: 'read', input: { filePath: '/tmp/demo.md' } },
|
||||
{ type: 'text', text: '1' },
|
||||
{ type: 'text', text: '1 2 3' },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
handleRuntimeEventState(h.set as never, h.get as never, {
|
||||
message: {
|
||||
role: 'toolResult',
|
||||
toolCallId: 'call-1',
|
||||
toolName: 'read',
|
||||
content: [{ type: 'text', text: 'done' }],
|
||||
},
|
||||
}, 'final', 'run-normalize');
|
||||
|
||||
expect(h.read().messages).toEqual([
|
||||
{
|
||||
role: 'assistant',
|
||||
id: 'streaming-assistant',
|
||||
content: [
|
||||
{ type: 'thinking', thinking: 'thinking 1 2 3' },
|
||||
{ type: 'tool_use', id: 'call-1', name: 'read', input: { filePath: '/tmp/demo.md' } },
|
||||
{ type: 'text', text: '1 2 3' },
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('clears runtime state on aborted event', async () => {
|
||||
const { handleRuntimeEventState } = await import('@/stores/chat/runtime-event-handlers');
|
||||
const h = makeHarness({
|
||||
|
||||
@@ -203,6 +203,31 @@ describe('deriveTaskSteps', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('collapses cumulative streaming thinking details into the newest version', () => {
|
||||
const steps = deriveTaskSteps({
|
||||
messages: [],
|
||||
streamingMessage: {
|
||||
role: 'assistant',
|
||||
content: [
|
||||
{ type: 'thinking', thinking: 'thinking 1' },
|
||||
{ type: 'thinking', thinking: 'thinking 1 2' },
|
||||
{ type: 'thinking', thinking: 'thinking 1 2 3' },
|
||||
],
|
||||
},
|
||||
streamingTools: [],
|
||||
sending: true,
|
||||
pendingFinal: false,
|
||||
showThinking: true,
|
||||
});
|
||||
|
||||
expect(steps).toEqual([
|
||||
expect.objectContaining({
|
||||
id: 'stream-thinking',
|
||||
detail: 'thinking 1 2 3',
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('builds a branch for spawned subagents', () => {
|
||||
const messages: RawMessage[] = [
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user