Compare commits

...
Author SHA1 Message Date
Yansong Zhang 9a06a45866 fix(agent): preserve roster answer after completion 2026-07-10 10:17:06 +08:00
4 changed files with 118 additions and 9 deletions
@@ -2010,7 +2010,7 @@ describe('useChat', () => {
})
const lastResponse = result.current.chatList[1]
expect(lastResponse!.content).toBe('')
expect(lastResponse!.content).toBe('history top-level answer')
expect(lastResponse!.agent_response_parts).toBeUndefined()
expect(lastResponse!.workflow_run_id).toBe('history-workflow-run')
expect(lastResponse!.workflowProcess).toBeUndefined()
@@ -2028,6 +2028,71 @@ describe('useChat', () => {
])
})
it('should keep new agent streaming response parts when completed history has no answer yet', async () => {
let callbacks: HookCallbacks
vi.mocked(ssePost).mockImplementation(async (_url, _params, options) => {
callbacks = options as HookCallbacks
})
const onGetConversationMessages = vi.fn().mockResolvedValue({
data: [{
id: 'm-new-agent-empty-history',
answer: '',
message: [{ role: 'user', text: 'hi' }],
agent_thoughts: [
{
id: 'history-thought',
thought: 'history thought',
answer: '',
tool: '',
tool_input: '',
observation: '',
position: 1,
},
],
created_at: Date.now(),
inputs: {},
query: 'hi',
}],
})
const { result } = renderHook(() => useChat(
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
{ isNewAgent: true },
))
act(() => {
result.current.handleSend('test-url', { query: 'new agent empty history' }, {
onGetConversationMessages,
})
})
await act(async () => {
callbacks.onThought({ id: 'stream-thought', thought: 'stream thought' })
callbacks.onData(' streamed answer', true, { event: 'agent_message', messageId: 'm-new-agent-empty-history', conversationId: 'c-new-agent-empty-history' })
await callbacks.onCompleted()
})
const lastResponse = result.current.chatList[1]
expect(lastResponse!.content).toBe('')
expect(lastResponse!.agent_response_parts).toEqual([
{ type: 'thought', thought: expect.objectContaining({ id: 'stream-thought', thought: 'stream thought' }) },
{ type: 'message', content: ' streamed answer' },
])
expect(lastResponse!.agent_thoughts).toEqual([
expect.objectContaining({
id: 'history-thought',
thought: 'history thought',
}),
])
})
it('should handle onCompleted using agent thought when thought matches answer', async () => {
let callbacks: HookCallbacks
vi.mocked(ssePost).mockImplementation(async (_url, _params, options) => {
@@ -38,7 +38,9 @@ describe('AgentRosterResponseContent', () => {
render(<AgentRosterResponseContent item={item} />)
expect(screen.getByRole('button', { name: /workFinished/i })).toBeInTheDocument()
expect(screen.queryByText('history answer')).not.toBeInTheDocument()
await waitFor(() => {
expect(screen.getByTestId('agent-roster-response-content')).toHaveTextContent('history answer')
})
fireEvent.click(screen.getByRole('button', { name: /workFinished/i }))
@@ -47,6 +49,7 @@ describe('AgentRosterResponseContent', () => {
})
expect(screen.queryByText('internal thought should not render')).not.toBeInTheDocument()
expect(screen.getAllByTestId('agent-content-markdown')).toHaveLength(1)
})
it('should render new agent response parts in event order when thoughts and messages interleave', async () => {
@@ -259,9 +259,11 @@ function ToolProcessCard({
function AgentThoughtsProcessList({
item,
responding,
suppressAnswer,
}: {
item: ChatItem
responding?: boolean
suppressAnswer?: boolean
}) {
return (
<div className="mt-2 flex flex-col gap-1">
@@ -271,6 +273,7 @@ function AgentThoughtsProcessList({
thought={thought}
responding={responding}
defaultOpen={index === 0}
suppressAnswer={suppressAnswer}
/>
))}
</div>
@@ -281,17 +284,19 @@ function AgentThoughtProcessItem({
thought,
responding,
defaultOpen,
suppressAnswer,
}: {
thought: ThoughtItem
responding?: boolean
defaultOpen?: boolean
suppressAnswer?: boolean
}) {
const tools = getToolProcesses(thought, responding)
const answer = thought.answer?.trim()
return (
<div className="flex flex-col gap-1">
{answer && (
{answer && !suppressAnswer && (
<div className="px-2 py-2 body-md-regular text-text-primary" data-testid="agent-content-markdown">
<Markdown content={thought.answer || ''} />
</div>
@@ -365,9 +370,11 @@ function AgentResponsePartList({
function AgentThoughtsProcessGroup({
item,
responding,
suppressAnswer,
}: {
item: ChatItem
responding?: boolean
suppressAnswer?: boolean
}) {
const { t } = useTranslation('agentV2')
const [open, setOpen] = useState(false)
@@ -385,6 +392,7 @@ function AgentThoughtsProcessGroup({
<AgentThoughtsProcessList
item={item}
responding={responding}
suppressAnswer={suppressAnswer}
/>
</div>
)
@@ -409,12 +417,26 @@ function AgentThoughtsProcessGroup({
<AgentThoughtsProcessList
item={item}
responding={responding}
suppressAnswer={suppressAnswer}
/>
)}
</div>
)
}
function getLastAgentThoughtAnswer(agentThoughts: ChatItem['agent_thoughts']) {
if (!agentThoughts?.length)
return ''
for (let index = agentThoughts.length - 1; index >= 0; index--) {
const answer = agentThoughts[index]?.answer?.trim()
if (answer)
return agentThoughts[index]?.answer || ''
}
return ''
}
export function AgentRosterResponseContent({
item,
responding,
@@ -434,6 +456,8 @@ export function AgentRosterResponseContent({
)
}
const visibleContent = content || getLastAgentThoughtAnswer(agent_thoughts)
return (
<div className="flex w-full flex-col gap-1" data-testid="agent-roster-response-content">
{!!item.agent_response_parts?.length && (
@@ -448,11 +472,12 @@ export function AgentRosterResponseContent({
<AgentThoughtsProcessGroup
item={item}
responding={responding}
suppressAnswer={!!visibleContent}
/>
)}
{content && (
{visibleContent && (
<div className="px-2 py-2 body-md-regular text-text-primary" data-testid="agent-content-markdown">
<Markdown content={content} />
<Markdown content={visibleContent} />
</div>
)}
</>
+20 -4
View File
@@ -134,6 +134,20 @@ function upsertAgentResponseThoughtPart(responseItem: ChatItemInTree, thought: T
})
}
function getLastAgentThoughtAnswer(agentThoughts: ThoughtItem[]) {
for (let index = agentThoughts.length - 1; index >= 0; index--) {
const answer = agentThoughts[index]?.answer?.trim()
if (answer)
return agentThoughts[index]?.answer || ''
}
return ''
}
function hasAgentResponseMessagePart(responseItem: ChatItem) {
return responseItem.agent_response_parts?.some(part => part.type === 'message' && !!part.content.trim()) ?? false
}
function getHistoryAgentThoughts(responseItem: HistoryConversationMessage) {
if (!Array.isArray(responseItem.agent_thoughts))
return []
@@ -984,19 +998,21 @@ export const useChat = (
return onConversationComplete?.(conversationIdRef.current, completedWorkflowRunId)
const historyAgentThoughts = getHistoryAgentThoughts(newResponseItem)
const hasHistoryAgentThoughtAnswer = historyAgentThoughts.some(thought => thought.answer?.trim())
const lastHistoryAgentThought = historyAgentThoughts.at(-1)
const historyAnswer = newResponseItem.answer || ''
const isUseAgentThought = (lastHistoryAgentThought?.thought === historyAnswer) || (options.isNewAgent && hasHistoryAgentThoughtAnswer)
const historyAgentThoughtAnswer = options.isNewAgent ? getLastAgentThoughtAnswer(historyAgentThoughts) : ''
const completedAnswer = historyAnswer || historyAgentThoughtAnswer
const isUseAgentThought = !options.isNewAgent && lastHistoryAgentThought?.thought === historyAnswer
const shouldKeepStreamingResponseParts = options.isNewAgent && !completedAnswer.trim() && hasAgentResponseMessagePart(responseItem)
const messageLog = Array.isArray(newResponseItem.message) ? newResponseItem.message : []
const answerTokens = newResponseItem.answer_tokens ?? 0
const messageTokens = newResponseItem.message_tokens ?? 0
const providerResponseLatency = newResponseItem.provider_response_latency ?? 0
const historyAnswerFiles = getHistoryAnswerFiles(newResponseItem)
updateChatTreeNode(responseItem.id, {
content: isUseAgentThought ? '' : historyAnswer,
content: shouldKeepStreamingResponseParts || isUseAgentThought ? '' : completedAnswer,
agent_thoughts: historyAgentThoughts,
agent_response_parts: undefined,
agent_response_parts: shouldKeepStreamingResponseParts ? responseItem.agent_response_parts : undefined,
citation: newResponseItem.retriever_resources,
reasoningContent: newResponseItem.metadata?.reasoning,
reasoningFinished: true,