feat(chat): refactor agent stream display and tool result rendering
Add RagPipelineProgress timeline, simplify AgentStreamDisplay structure, group grep hits per document, and add KnowledgeChunksList tool result UI.
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { getAgentToolIconName } from './agent-tool-icons.ts'
|
||||
import {
|
||||
getKnowledgeSearchSummaryHtml,
|
||||
getQueryText,
|
||||
getRagPipelineStepTitle,
|
||||
} from './agent-tool-display.ts'
|
||||
|
||||
const t = (key, params) => {
|
||||
if (key === 'agentStream.search.foundResultsFromFiles') {
|
||||
return `found ${params?.count} from ${params?.files} files`
|
||||
}
|
||||
if (key === 'agentStream.ragPipeline.searchingWithQuery') {
|
||||
return `searching ${params?.query}`
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
test('getAgentToolIconName maps rag pipeline tools', () => {
|
||||
assert.equal(getAgentToolIconName('query_understand'), 'ai-search')
|
||||
assert.equal(getAgentToolIconName('knowledge_search'), 'data-search')
|
||||
})
|
||||
|
||||
test('getQueryText joins unique query strings', () => {
|
||||
assert.equal(getQueryText({ query: 'foo', queries: ['foo', 'bar'] }), 'foo,bar')
|
||||
})
|
||||
|
||||
test('getQueryText parses JSON-encoded queries string', () => {
|
||||
assert.equal(
|
||||
getQueryText({
|
||||
queries: '["合力天胜游泳俱乐部介绍", "合力天胜游泳训练机构", "合力天胜游泳队"]',
|
||||
}),
|
||||
'合力天胜游泳俱乐部介绍,合力天胜游泳训练机构,合力天胜游泳队',
|
||||
)
|
||||
})
|
||||
|
||||
test('getKnowledgeSearchSummaryHtml includes file count when present', () => {
|
||||
const html = getKnowledgeSearchSummaryHtml(t, {
|
||||
results: [{}, {}],
|
||||
kb_counts: { a: 1, b: 2 },
|
||||
})
|
||||
assert.match(html, /found <strong>2<\/strong> from <strong>2<\/strong> files/)
|
||||
})
|
||||
|
||||
test('getRagPipelineStepTitle uses query-aware search labels', () => {
|
||||
const title = getRagPipelineStepTitle(t, {
|
||||
tool_name: 'knowledge_search',
|
||||
pending: true,
|
||||
arguments: { query: '讯飞开放平台' },
|
||||
})
|
||||
assert.equal(title, 'searching 讯飞开放平台')
|
||||
})
|
||||
@@ -0,0 +1,109 @@
|
||||
import type { ComposerTranslation } from 'vue-i18n'
|
||||
|
||||
function collectQueryStrings(value: unknown): string[] {
|
||||
if (value == null) return []
|
||||
|
||||
if (typeof value === 'string') {
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed) return []
|
||||
if (trimmed.startsWith('[')) {
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed)
|
||||
if (Array.isArray(parsed)) {
|
||||
return parsed.filter((q): q is string => typeof q === 'string' && Boolean(q.trim()))
|
||||
}
|
||||
} catch {
|
||||
// fall through to treat as a single query string
|
||||
}
|
||||
}
|
||||
return [trimmed]
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.filter((q): q is string => typeof q === 'string' && Boolean(q.trim()))
|
||||
}
|
||||
|
||||
return []
|
||||
}
|
||||
|
||||
export function getQueryText(args: unknown): string {
|
||||
if (!args) return ''
|
||||
|
||||
let parsedArgs = args
|
||||
if (typeof parsedArgs === 'string') {
|
||||
try {
|
||||
parsedArgs = JSON.parse(parsedArgs)
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
if (!parsedArgs || typeof parsedArgs !== 'object') return ''
|
||||
|
||||
const queries: string[] = []
|
||||
const record = parsedArgs as Record<string, unknown>
|
||||
|
||||
queries.push(...collectQueryStrings(record.query))
|
||||
queries.push(...collectQueryStrings(record.queries))
|
||||
|
||||
return Array.from(new Set(queries)).join(',')
|
||||
}
|
||||
|
||||
export function getKnowledgeSearchSummaryHtml(
|
||||
t: ComposerTranslation,
|
||||
toolData: Record<string, unknown> | null | undefined,
|
||||
): string {
|
||||
if (!toolData) return ''
|
||||
|
||||
const results = toolData.results
|
||||
const count = (Array.isArray(results) ? results.length : 0) || Number(toolData.count) || 0
|
||||
if (count === 0) return t('agentStream.search.noResults')
|
||||
|
||||
const kbCounts = toolData.kb_counts
|
||||
const kbCount = kbCounts && typeof kbCounts === 'object' ? Object.keys(kbCounts).length : 0
|
||||
if (kbCount > 0) {
|
||||
return t('agentStream.search.foundResultsFromFiles', {
|
||||
count: `<strong>${count}</strong>`,
|
||||
files: `<strong>${kbCount}</strong>`,
|
||||
})
|
||||
}
|
||||
|
||||
return t('agentStream.search.foundResults', { count: `<strong>${count}</strong>` })
|
||||
}
|
||||
|
||||
type RagPipelineEvent = {
|
||||
tool_name?: string
|
||||
pending?: boolean
|
||||
success?: boolean
|
||||
arguments?: unknown
|
||||
tool_data?: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
export function getRagPipelineStepTitle(t: ComposerTranslation, event: RagPipelineEvent): string {
|
||||
const toolName = String(event.tool_name || '')
|
||||
const pending = event.pending === true
|
||||
const query =
|
||||
getQueryText(event.arguments) ||
|
||||
getQueryText(event.tool_data)
|
||||
|
||||
if (toolName === 'query_understand') {
|
||||
return pending
|
||||
? t('agentStream.toolStatus.queryUnderstanding')
|
||||
: t('agentStream.toolStatus.queryUnderstandDone')
|
||||
}
|
||||
|
||||
if (toolName === 'knowledge_search' || toolName === 'search_knowledge') {
|
||||
if (pending) {
|
||||
return query
|
||||
? t('agentStream.ragPipeline.searchingWithQuery', { query })
|
||||
: t('agentStream.ragPipeline.searching')
|
||||
}
|
||||
|
||||
const baseTitle = event.success === false
|
||||
? t('agentStream.toolStatus.searchKbFailed')
|
||||
: t('agentStream.toolStatus.searchKb')
|
||||
return query ? `${baseTitle}:「${query}」` : baseTitle
|
||||
}
|
||||
|
||||
return ''
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/** TDesign icon names for agent / RAG pipeline tool steps. */
|
||||
export function getAgentToolIconName(toolName: string): string {
|
||||
if (toolName === 'thinking') {
|
||||
return 'ai-search'
|
||||
}
|
||||
if (toolName === 'search_knowledge' || toolName === 'knowledge_search') {
|
||||
return 'data-search'
|
||||
}
|
||||
if (toolName === 'grep_chunks') {
|
||||
return 'search'
|
||||
}
|
||||
if (toolName === 'web_search') {
|
||||
return 'internet'
|
||||
}
|
||||
if (toolName === 'get_document_info' || toolName === 'list_knowledge_chunks') {
|
||||
return 'file-search'
|
||||
}
|
||||
if (toolName === 'get_document_content' || toolName === 'wiki_read_source_doc') {
|
||||
return 'file-search'
|
||||
}
|
||||
if (toolName === 'todo_write') {
|
||||
return 'task'
|
||||
}
|
||||
if (toolName === 'image_analysis' || toolName === 'query_understand') {
|
||||
return 'ai-search'
|
||||
}
|
||||
if (toolName.startsWith('mcp_')) {
|
||||
return 'terminal'
|
||||
}
|
||||
return 'file-paste'
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { countGrepDocuments, groupGrepChunkResults } from './grepResultsGroup.ts'
|
||||
|
||||
test('groupGrepChunkResults merges chunks from the same document', () => {
|
||||
const grouped = groupGrepChunkResults([
|
||||
{
|
||||
chunk_id: 'chunk-a',
|
||||
knowledge_id: 'doc-1',
|
||||
knowledge_base_id: 'kb-1',
|
||||
knowledge_title: 'sample-report.pdf',
|
||||
match_snippet: 'hit one',
|
||||
},
|
||||
{
|
||||
chunk_id: 'chunk-b',
|
||||
knowledge_id: 'doc-1',
|
||||
knowledge_base_id: 'kb-1',
|
||||
knowledge_title: 'sample-report.pdf',
|
||||
match_snippet: 'hit two',
|
||||
},
|
||||
{
|
||||
chunk_id: 'chunk-c',
|
||||
knowledge_id: 'doc-2',
|
||||
knowledge_base_id: 'kb-1',
|
||||
knowledge_title: 'other-report.pdf',
|
||||
match_snippet: 'other hit',
|
||||
},
|
||||
])
|
||||
|
||||
assert.equal(grouped.length, 2)
|
||||
assert.equal(grouped[0].chunk_hit_count, 2)
|
||||
assert.equal(grouped[0].chunks.length, 2)
|
||||
assert.equal(grouped[1].chunk_hit_count, 1)
|
||||
})
|
||||
|
||||
test('groupGrepChunkResults keeps FAQ entries separate', () => {
|
||||
const grouped = groupGrepChunkResults([
|
||||
{
|
||||
chunk_id: 'faq-1',
|
||||
faq_id: 'faq-1',
|
||||
knowledge_id: 'doc-faq',
|
||||
knowledge_base_id: 'kb-1',
|
||||
knowledge_title: 'FAQ doc',
|
||||
chunk_type: 'faq',
|
||||
faq_question: 'Question A',
|
||||
match_snippet: 'answer a',
|
||||
},
|
||||
{
|
||||
chunk_id: 'faq-2',
|
||||
faq_id: 'faq-2',
|
||||
knowledge_id: 'doc-faq',
|
||||
knowledge_base_id: 'kb-1',
|
||||
knowledge_title: 'FAQ doc',
|
||||
chunk_type: 'faq',
|
||||
faq_question: 'Question B',
|
||||
match_snippet: 'answer b',
|
||||
},
|
||||
])
|
||||
|
||||
assert.equal(grouped.length, 2)
|
||||
assert.equal(grouped[0].title, 'Question A')
|
||||
assert.equal(grouped[1].title, 'Question B')
|
||||
})
|
||||
|
||||
test('countGrepDocuments prefers document_count from backend', () => {
|
||||
assert.equal(
|
||||
countGrepDocuments({
|
||||
document_count: 1,
|
||||
knowledge_results: [{ knowledge_id: 'doc-1' }, { knowledge_id: 'doc-2' }],
|
||||
chunk_results: [{ chunk_id: 'c1', knowledge_id: 'doc-1', knowledge_base_id: 'kb', knowledge_title: 'a' }],
|
||||
}),
|
||||
1,
|
||||
)
|
||||
})
|
||||
|
||||
test('countGrepDocuments prefers knowledge_results length when document_count absent', () => {
|
||||
assert.equal(
|
||||
countGrepDocuments({
|
||||
knowledge_results: [{ knowledge_id: 'doc-1' }, { knowledge_id: 'doc-2' }],
|
||||
chunk_results: [{ chunk_id: 'c1', knowledge_id: 'doc-1', knowledge_base_id: 'kb', knowledge_title: 'a' }],
|
||||
}),
|
||||
2,
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { GrepChunkResult, GrepKnowledgeResult } from '@/types/tool-results'
|
||||
|
||||
export type GrepGroupedRow = {
|
||||
key: string
|
||||
knowledge_id: string
|
||||
title: string
|
||||
is_faq: boolean
|
||||
chunk_hit_count: number
|
||||
title_match: boolean
|
||||
match_snippet: string
|
||||
chunks: { content: string; chunk_id: string; knowledge_id: string }[]
|
||||
}
|
||||
|
||||
/** Collapse per-chunk grep hits into one row per document; FAQ entries stay separate. */
|
||||
export function groupGrepChunkResults(chunkRows: GrepChunkResult[]): GrepGroupedRow[] {
|
||||
const map = new Map<string, GrepGroupedRow>()
|
||||
const order: string[] = []
|
||||
|
||||
for (const result of chunkRows) {
|
||||
const isFAQ = !!result.faq_id || result.chunk_type === 'faq'
|
||||
const key = isFAQ ? (result.faq_id || result.chunk_id) : result.knowledge_id
|
||||
if (!key) continue
|
||||
|
||||
const snippet = String(result.match_snippet ?? '').trim()
|
||||
if (!map.has(key)) {
|
||||
map.set(key, {
|
||||
key,
|
||||
knowledge_id: result.knowledge_id,
|
||||
title: result.faq_question || result.knowledge_title || '',
|
||||
is_faq: isFAQ,
|
||||
chunk_hit_count: 0,
|
||||
title_match: false,
|
||||
match_snippet: snippet,
|
||||
chunks: [],
|
||||
})
|
||||
order.push(key)
|
||||
}
|
||||
|
||||
const group = map.get(key)!
|
||||
group.chunk_hit_count += 1
|
||||
if (result.title_match) group.title_match = true
|
||||
if (!group.match_snippet && snippet) group.match_snippet = snippet
|
||||
if (snippet) {
|
||||
group.chunks.push({
|
||||
content: snippet,
|
||||
chunk_id: result.faq_id || result.chunk_id,
|
||||
knowledge_id: result.knowledge_id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return order.map((key) => map.get(key)!)
|
||||
}
|
||||
|
||||
export function countGrepDocuments(toolData: {
|
||||
document_count?: number
|
||||
knowledge_results?: GrepKnowledgeResult[]
|
||||
chunk_results?: GrepChunkResult[]
|
||||
} | null | undefined): number {
|
||||
if (!toolData) return 0
|
||||
if (typeof toolData.document_count === 'number' && toolData.document_count >= 0) {
|
||||
return toolData.document_count
|
||||
}
|
||||
if (toolData.knowledge_results?.length) {
|
||||
return toolData.knowledge_results.length
|
||||
}
|
||||
if (toolData.chunk_results?.length) {
|
||||
return groupGrepChunkResults(toolData.chunk_results).length
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { getKnowledgeChunksSummaryHtml } from './knowledgeChunksDisplay.ts'
|
||||
|
||||
const t = (key, params) => {
|
||||
if (key === 'agentStream.knowledgeChunksList.chunkRange') {
|
||||
return `loaded ${params?.fetched}/${params?.total}`
|
||||
}
|
||||
if (key === 'agentStream.knowledgeChunksList.page') {
|
||||
return `page ${params?.page}/${params?.pageSize}`
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
test('getKnowledgeChunksSummaryHtml joins chunk range and page', () => {
|
||||
const html = getKnowledgeChunksSummaryHtml(t, {
|
||||
display_type: 'knowledge_chunks_list',
|
||||
fetched_chunks: 20,
|
||||
total_chunks: 282,
|
||||
page: 3,
|
||||
page_size: 20,
|
||||
})
|
||||
assert.match(html, /loaded <strong>20<\/strong>\/<strong>282<\/strong>/)
|
||||
assert.match(html, /page 3\/20/)
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { ComposerTranslation } from 'vue-i18n'
|
||||
|
||||
import type { KnowledgeChunksListData } from '@/types/tool-results'
|
||||
|
||||
export function getKnowledgeChunksSummaryHtml(
|
||||
t: ComposerTranslation,
|
||||
toolData: KnowledgeChunksListData | null | undefined,
|
||||
): string {
|
||||
if (!toolData || toolData.fetched_chunks === undefined) {
|
||||
return ''
|
||||
}
|
||||
|
||||
const parts: string[] = [
|
||||
t('agentStream.knowledgeChunksList.chunkRange', {
|
||||
fetched: `<strong>${toolData.fetched_chunks ?? 0}</strong>`,
|
||||
total: `<strong>${toolData.total_chunks ?? '?'}</strong>`,
|
||||
}),
|
||||
]
|
||||
|
||||
const total = Number(toolData.total_chunks ?? 0)
|
||||
const pageSize = Number(toolData.page_size ?? 0)
|
||||
if (total > pageSize && pageSize > 0) {
|
||||
parts.push(
|
||||
t('agentStream.knowledgeChunksList.page', {
|
||||
page: toolData.page ?? 1,
|
||||
pageSize,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
return parts.join(' · ')
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import {
|
||||
ensureRagPipelineHistoryStream,
|
||||
hasRagPipelineToolEvents,
|
||||
synthesizeRagPipelineToolEvents,
|
||||
} from './rag-pipeline-history.ts'
|
||||
|
||||
test('synthesizeRagPipelineToolEvents builds completed retrieval steps', () => {
|
||||
const events = synthesizeRagPipelineToolEvents({
|
||||
knowledge_references: [
|
||||
{ knowledge_id: 'a' },
|
||||
{ knowledge_id: 'a' },
|
||||
{ knowledge_id: 'b' },
|
||||
],
|
||||
})
|
||||
|
||||
assert.equal(events.length, 2)
|
||||
assert.equal(events[0].tool_name, 'query_understand')
|
||||
assert.equal(events[1].tool_name, 'knowledge_search')
|
||||
assert.equal(events[1].tool_data.count, 3)
|
||||
})
|
||||
|
||||
test('ensureRagPipelineHistoryStream restores quick-answer history after reload', () => {
|
||||
const item = {
|
||||
is_completed: true,
|
||||
content: 'final answer',
|
||||
knowledge_references: [{ knowledge_id: 'doc-1' }],
|
||||
agentEventStream: [],
|
||||
}
|
||||
|
||||
ensureRagPipelineHistoryStream(item)
|
||||
|
||||
assert.equal(item.isAgentMode, true)
|
||||
assert.equal(item.hideContent, true)
|
||||
assert.equal(hasRagPipelineToolEvents(item.agentEventStream), true)
|
||||
assert.equal(
|
||||
item.agentEventStream.some((event) => event.type === 'answer'),
|
||||
true,
|
||||
)
|
||||
})
|
||||
|
||||
test('ensureRagPipelineHistoryStream keeps existing pipeline events', () => {
|
||||
const existing = {
|
||||
type: 'tool_call',
|
||||
tool_name: 'knowledge_search',
|
||||
tool_call_id: 'live-1',
|
||||
pending: false,
|
||||
}
|
||||
const item = {
|
||||
is_completed: true,
|
||||
content: 'answer',
|
||||
agentEventStream: [existing],
|
||||
}
|
||||
|
||||
ensureRagPipelineHistoryStream(item)
|
||||
|
||||
assert.equal(item.agentEventStream.length, 1)
|
||||
assert.equal(item.agentEventStream[0].tool_call_id, 'live-1')
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
export const RAG_PIPELINE_TOOL_NAMES = new Set(['query_understand', 'knowledge_search'])
|
||||
|
||||
type RagHistoryMessage = {
|
||||
knowledge_references?: Array<{
|
||||
chunk_type?: string
|
||||
knowledge_id?: string
|
||||
knowledge_title?: string
|
||||
}>
|
||||
agentEventStream?: Array<Record<string, unknown>>
|
||||
}
|
||||
|
||||
export function hasRagPipelineToolEvents(stream: Array<Record<string, unknown>> | undefined): boolean {
|
||||
if (!stream?.length) return false
|
||||
return stream.some((event) => {
|
||||
return (
|
||||
event.type === 'tool_call' &&
|
||||
typeof event.tool_name === 'string' &&
|
||||
RAG_PIPELINE_TOOL_NAMES.has(event.tool_name)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
export function synthesizeRagPipelineToolEvents(
|
||||
item: RagHistoryMessage,
|
||||
): Array<Record<string, unknown>> {
|
||||
const refs = item.knowledge_references ?? []
|
||||
const kbCounts: Record<string, number> = {}
|
||||
|
||||
for (const ref of refs) {
|
||||
if (ref.chunk_type === 'web_search') continue
|
||||
const key = ref.knowledge_id || ref.knowledge_title || 'document'
|
||||
kbCounts[key] = (kbCounts[key] || 0) + 1
|
||||
}
|
||||
|
||||
const events: Array<Record<string, unknown>> = [
|
||||
{
|
||||
type: 'tool_call',
|
||||
tool_call_id: 'rag-history-query-understand',
|
||||
tool_name: 'query_understand',
|
||||
pending: false,
|
||||
success: true,
|
||||
},
|
||||
{
|
||||
type: 'tool_call',
|
||||
tool_call_id: 'rag-history-knowledge-search',
|
||||
tool_name: 'knowledge_search',
|
||||
pending: false,
|
||||
success: true,
|
||||
tool_data: {
|
||||
count: refs.length,
|
||||
kb_counts: kbCounts,
|
||||
results: refs,
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
return events
|
||||
}
|
||||
|
||||
export function ensureRagPipelineHistoryStream(item: RagHistoryMessage & {
|
||||
content?: string
|
||||
is_completed?: boolean
|
||||
isAgentMode?: boolean
|
||||
hideContent?: boolean
|
||||
}): void {
|
||||
if (!item.is_completed) return
|
||||
|
||||
const stream = Array.isArray(item.agentEventStream)
|
||||
? [...item.agentEventStream]
|
||||
: []
|
||||
|
||||
if (hasRagPipelineToolEvents(stream)) return
|
||||
|
||||
const hasRestorablePayload =
|
||||
Boolean(item.content?.trim()) ||
|
||||
Boolean(item.knowledge_references?.length)
|
||||
if (!hasRestorablePayload) return
|
||||
|
||||
const synthesized = synthesizeRagPipelineToolEvents(item)
|
||||
const preserved = stream.filter((event) => {
|
||||
return !(
|
||||
event.type === 'tool_call' &&
|
||||
typeof event.tool_name === 'string' &&
|
||||
RAG_PIPELINE_TOOL_NAMES.has(event.tool_name)
|
||||
)
|
||||
})
|
||||
|
||||
item.agentEventStream = [...synthesized, ...preserved]
|
||||
|
||||
const hasAnswer = preserved.some((event) => {
|
||||
if (event.type !== 'answer' || event.superseded) return false
|
||||
const content = event.content
|
||||
return typeof content === 'string' && content.trim().length > 0
|
||||
})
|
||||
|
||||
if (!hasAnswer && item.content?.trim()) {
|
||||
item.agentEventStream.push({
|
||||
type: 'answer',
|
||||
content: item.content,
|
||||
done: true,
|
||||
})
|
||||
}
|
||||
|
||||
item.isAgentMode = true
|
||||
item.hideContent = true
|
||||
}
|
||||
Reference in New Issue
Block a user