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:
Haze
2026-04-18 15:23:16 +08:00
committed by GitHub
Unverified
parent 6d67a77633
commit 24b43335f8
12 changed files with 789 additions and 119 deletions

View File

@@ -16,7 +16,7 @@ function stableStringify(value: unknown): string {
const seededHistory = [
{
role: 'user',
content: [{ type: 'text', text: '[Mon 2026-04-06 15:18 GMT+8] 分析 Velaria 当前未提交改动' }],
content: [{ type: 'text', text: '[Mon 2026-04-06 15:18 GMT+8] Analyze Velaria uncommitted changes' }],
timestamp: Date.now(),
},
{
@@ -57,7 +57,7 @@ const seededHistory = [
type: 'toolCall',
id: 'yield-call',
name: 'sessions_yield',
arguments: { message: '我让 coder 去拆 ~/Velaria 当前未提交改动的核心块了,等它回来我直接给你结论。' },
arguments: { message: 'I asked coder to break down the core blocks of ~/Velaria uncommitted changes; will give you the conclusion when it returns.' },
}],
timestamp: Date.now(),
},
@@ -69,12 +69,12 @@ const seededHistory = [
type: 'text',
text: JSON.stringify({
status: 'yielded',
message: '我让 coder 去拆 ~/Velaria 当前未提交改动的核心块了,等它回来我直接给你结论。',
message: 'I asked coder to break down the core blocks of ~/Velaria uncommitted changes; will give you the conclusion when it returns.',
}, null, 2),
}],
details: {
status: 'yielded',
message: '我让 coder 去拆 ~/Velaria 当前未提交改动的核心块了,等它回来我直接给你结论。',
message: 'I asked coder to break down the core blocks of ~/Velaria uncommitted changes; will give you the conclusion when it returns.',
},
isError: false,
timestamp: Date.now(),
@@ -94,7 +94,7 @@ status: completed successfully`,
},
{
role: 'assistant',
content: [{ type: 'text', text: '我让 coder 分析完了,下面是结论。' }],
content: [{ type: 'text', text: 'Coder has finished the analysis, here are the conclusions.' }],
_attachedFiles: [
{
fileName: 'CHECKLIST.md',
@@ -112,7 +112,7 @@ status: completed successfully`,
const childTranscriptMessages = [
{
role: 'user',
content: [{ type: 'text', text: '分析 ~/Velaria 当前未提交改动的核心内容' }],
content: [{ type: 'text', text: 'Analyze the core content of ~/Velaria uncommitted changes' }],
timestamp: Date.now(),
},
{
@@ -143,7 +143,7 @@ const childTranscriptMessages = [
},
{
role: 'assistant',
content: [{ type: 'text', text: '已完成分析,最关键的有 4 块。' }],
content: [{ type: 'text', text: 'Analysis complete, there are 4 key blocks.' }],
timestamp: Date.now(),
},
];
@@ -229,10 +229,145 @@ test.describe('ClawX chat execution graph', () => {
await expect(
page.locator('[data-testid="chat-execution-graph"] [data-testid="chat-execution-step"]').getByText('exec', { exact: true }),
).toBeVisible();
await expect(page.locator('[data-testid="chat-execution-graph"]').getByText('我让 coder 去拆 ~/Velaria 当前未提交改动的核心块了,等它回来我直接给你结论。')).toBeVisible();
await expect(page.locator('[data-testid="chat-execution-graph"]').getByText('I asked coder to break down the core blocks of ~/Velaria uncommitted changes; will give you the conclusion when it returns.')).toBeVisible();
await expect(page.getByText('CHECKLIST.md')).toHaveCount(0);
} finally {
await closeElectronApp(app);
}
});
test('does not duplicate the in-flight user prompt or cumulative streaming content', async ({ launchElectronApp }) => {
const app = await launchElectronApp({ skipSetup: true });
try {
await installIpcMocks(app, {
gatewayStatus: { state: 'running', port: 18789, pid: 12345 },
gatewayRpc: {
[stableStringify(['sessions.list', {}])]: {
success: true,
result: {
sessions: [{ key: PROJECT_MANAGER_SESSION_KEY, displayName: 'main' }],
},
},
[stableStringify(['chat.history', { sessionKey: PROJECT_MANAGER_SESSION_KEY, limit: 200 }])]: {
success: true,
result: {
messages: [],
},
},
},
hostApi: {
[stableStringify(['/api/gateway/status', 'GET'])]: {
ok: true,
data: {
status: 200,
ok: true,
json: { state: 'running', port: 18789, pid: 12345 },
},
},
[stableStringify(['/api/agents', 'GET'])]: {
ok: true,
data: {
status: 200,
ok: true,
json: {
success: true,
agents: [{ id: 'main', name: 'main' }],
},
},
},
},
});
await app.evaluate(async ({ app: _app }) => {
const { ipcMain } = process.mainModule!.require('electron') as typeof import('electron');
const sendPayloads: Array<{ message?: string; sessionKey?: string }> = [];
ipcMain.removeHandler('gateway:rpc');
ipcMain.handle('gateway:rpc', async (_event: unknown, method: string, payload: unknown) => {
if (method === 'sessions.list') {
return {
success: true,
result: {
sessions: [{ key: 'agent:main:main', displayName: 'main' }],
},
};
}
if (method === 'chat.history') {
return {
success: true,
result: { messages: [] },
};
}
if (method === 'chat.send') {
if (payload && typeof payload === 'object') {
const p = payload as { message?: string; sessionKey?: string };
sendPayloads.push({ message: p.message, sessionKey: p.sessionKey });
}
return {
success: true,
result: { runId: 'mock-run' },
};
}
return { success: true, result: {} };
});
(globalThis as typeof globalThis & { __clawxSendPayloads?: Array<{ message?: string; sessionKey?: string }> }).__clawxSendPayloads = sendPayloads;
});
const page = await getStableWindow(app);
try {
await page.reload();
} catch (error) {
if (!String(error).includes('ERR_FILE_NOT_FOUND')) {
throw error;
}
}
await expect(page.getByTestId('main-layout')).toBeVisible();
await page.getByTestId('chat-composer-input').fill('Open browser, search for tech news, and take a screenshot');
await page.getByTestId('chat-composer-send').click();
await expect(page.getByText('Open browser, search for tech news, and take a screenshot')).toHaveCount(1);
await expect.poll(async () => {
return await app.evaluate(() => {
const sendPayloads = (globalThis as typeof globalThis & {
__clawxSendPayloads?: Array<{ message?: string; sessionKey?: string }>;
}).__clawxSendPayloads || [];
return sendPayloads.length;
});
}).toBe(1);
await app.evaluate(async ({ BrowserWindow }) => {
const win = BrowserWindow.getAllWindows()[0];
win?.webContents.send('gateway:notification', {
method: 'agent',
params: {
runId: 'mock-run',
sessionKey: 'agent:main:main',
state: 'delta',
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' },
],
},
},
});
});
await expect(page.getByText('Open browser, search for tech news, and take a screenshot')).toHaveCount(1);
await expect(page.getByText(/^thinking 1 2 3$/)).toHaveCount(1);
await expect(page.getByText(/^thinking 1 2$/)).toHaveCount(0);
await expect(page.getByText(/^thinking 1$/)).toHaveCount(0);
await expect(page.getByText(/^1 2 3$/)).toHaveCount(1);
await expect(page.getByText(/^1 2$/)).toHaveCount(0);
await expect(page.getByText(/^1$/)).toHaveCount(0);
} finally {
await closeElectronApp(app);
}
});
});

View File

@@ -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',
]);
});
});

View File

@@ -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({

View File

@@ -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[] = [
{