From c6f1b54f731ee9cd88b65961c4730f47c4a3d177 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Tue, 16 Jun 2026 00:49:44 +0800 Subject: [PATCH] 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. --- .../components/css/chat-message-shared.less | 27 + .../components/css/chat-timeline-loading.less | 69 + .../css/chat-timeline-loading.test.mjs | 16 + .../src/composables/useChatStreamHandler.ts | 151 +- frontend/src/types/tool-results.ts | 17 + .../src/utils/agent-tool-display.test.mjs | 53 + frontend/src/utils/agent-tool-display.ts | 109 + frontend/src/utils/agent-tool-icons.ts | 31 + frontend/src/utils/grepResultsGroup.test.mjs | 85 + frontend/src/utils/grepResultsGroup.ts | 71 + .../src/utils/knowledgeChunksDisplay.test.mjs | 26 + frontend/src/utils/knowledgeChunksDisplay.ts | 32 + .../src/utils/rag-pipeline-history.test.mjs | 60 + frontend/src/utils/rag-pipeline-history.ts | 106 + .../AgentStreamDisplay.style.test.mjs | 80 + .../chat/components/AgentStreamDisplay.vue | 2442 +++++++---------- .../RagPipelineProgress.style.test.mjs | 67 + .../chat/components/RagPipelineProgress.vue | 534 ++++ .../chat/components/ToolResultRenderer.vue | 116 +- .../chat/components/docInfo.style.test.mjs | 18 + .../src/views/chat/components/docInfo.vue | 146 +- .../components/tool-results/GrepResults.vue | 70 +- .../tool-results/KnowledgeChunksList.vue | 43 + .../src/views/chat/components/usermsg.vue | 37 +- frontend/src/views/chat/index.vue | 207 +- 25 files changed, 2832 insertions(+), 1781 deletions(-) create mode 100644 frontend/src/components/css/chat-timeline-loading.less create mode 100644 frontend/src/components/css/chat-timeline-loading.test.mjs create mode 100644 frontend/src/utils/agent-tool-display.test.mjs create mode 100644 frontend/src/utils/agent-tool-display.ts create mode 100644 frontend/src/utils/agent-tool-icons.ts create mode 100644 frontend/src/utils/grepResultsGroup.test.mjs create mode 100644 frontend/src/utils/grepResultsGroup.ts create mode 100644 frontend/src/utils/knowledgeChunksDisplay.test.mjs create mode 100644 frontend/src/utils/knowledgeChunksDisplay.ts create mode 100644 frontend/src/utils/rag-pipeline-history.test.mjs create mode 100644 frontend/src/utils/rag-pipeline-history.ts create mode 100644 frontend/src/views/chat/components/AgentStreamDisplay.style.test.mjs create mode 100644 frontend/src/views/chat/components/RagPipelineProgress.style.test.mjs create mode 100644 frontend/src/views/chat/components/RagPipelineProgress.vue create mode 100644 frontend/src/views/chat/components/docInfo.style.test.mjs create mode 100644 frontend/src/views/chat/components/tool-results/KnowledgeChunksList.vue diff --git a/frontend/src/components/css/chat-message-shared.less b/frontend/src/components/css/chat-message-shared.less index 6d321c0f..1e2d7ee7 100644 --- a/frontend/src/components/css/chat-message-shared.less +++ b/frontend/src/components/css/chat-message-shared.less @@ -164,3 +164,30 @@ filter: saturate(1.06); } } + +:deep(.streaming-mermaid-loading) { + display: block; + position: relative; + width: 100%; + max-width: 480px; + min-height: 180px; + margin: 0.75em 0; + border-radius: 0; + border: 0; + background: var(--td-bg-color-container); + overflow: hidden; + animation: streamingImageBreath 2.2s ease-in-out infinite; +} + +:deep(.streaming-mermaid-loading__skeleton) { + position: absolute; + inset: 0; + background: linear-gradient( + 110deg, + rgba(234, 239, 246, 0.95) 8%, + rgba(248, 250, 252, 0.98) 18%, + rgba(234, 239, 246, 0.95) 33% + ); + background-size: 220% 100%; + animation: streamingImageShimmer 1.4s linear infinite; +} diff --git a/frontend/src/components/css/chat-timeline-loading.less b/frontend/src/components/css/chat-timeline-loading.less new file mode 100644 index 00000000..e4f7dbcd --- /dev/null +++ b/frontend/src/components/css/chat-timeline-loading.less @@ -0,0 +1,69 @@ +@keyframes chatTimelineTypingBounce { + + 0%, + 60%, + 100% { + transform: translateY(0); + } + + 30% { + transform: translateY(-8px); + } +} + +@keyframes chatTimelineLoadingFadeIn { + from { + opacity: 0; + transform: translateY(6px); + } + + to { + opacity: 1; + transform: translateY(0); + } +} + +.streaming-loading-node { + .tree-child-content { + position: relative; + } + + .loading-indicator { + display: flex; + align-items: center; + min-height: 24px; + padding: 0; + margin: 0; + position: relative; + animation: chatTimelineLoadingFadeIn 0.3s ease-out; + } + + .loading-typing { + position: absolute; + left: -42px; + top: 9px; + display: flex; + align-items: center; + gap: 4px; + + span { + width: 4px; + height: 4px; + border-radius: 50%; + background: var(--td-text-color-placeholder); + animation: chatTimelineTypingBounce 1.4s ease-in-out infinite; + + &:nth-child(1) { + animation-delay: 0s; + } + + &:nth-child(2) { + animation-delay: 0.2s; + } + + &:nth-child(3) { + animation-delay: 0.4s; + } + } + } +} diff --git a/frontend/src/components/css/chat-timeline-loading.test.mjs b/frontend/src/components/css/chat-timeline-loading.test.mjs new file mode 100644 index 00000000..01e80735 --- /dev/null +++ b/frontend/src/components/css/chat-timeline-loading.test.mjs @@ -0,0 +1,16 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import test from 'node:test' + +const here = dirname(fileURLToPath(import.meta.url)) +const css = readFileSync(join(here, 'chat-timeline-loading.less'), 'utf8') + +test('timeline loading uses shared gray bounce dots on the axis', () => { + assert.match(css, /\.streaming-loading-node\s*\{[\s\S]*left:\s*-42px/) + assert.match(css, /width:\s*4px/) + assert.match(css, /background:\s*var\(--td-text-color-placeholder\)/) + assert.match(css, /animation:\s*chatTimelineTypingBounce/) + assert.match(css, /animation-delay:\s*0\.2s/) +}) diff --git a/frontend/src/composables/useChatStreamHandler.ts b/frontend/src/composables/useChatStreamHandler.ts index b1842664..dabc043b 100644 --- a/frontend/src/composables/useChatStreamHandler.ts +++ b/frontend/src/composables/useChatStreamHandler.ts @@ -1,5 +1,6 @@ import { markRaw, nextTick, type Ref } from 'vue' import { useI18n } from 'vue-i18n' +import { ensureRagPipelineHistoryStream } from '@/utils/rag-pipeline-history' export type ChatMessage = Record @@ -66,8 +67,74 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { return undefined } + const extractKnowledgeReferences = (data: ChatMessage) => { + const dataPayload = data.data as ChatMessage | undefined + const refs = + data.knowledge_references || + dataPayload?.references || + dataPayload?.knowledge_references || + [] + return Array.isArray(refs) ? refs : [] + } + + /** Match the in-flight assistant row by request id or assistant message id. */ + const resolveActiveAssistantMessage = (data: ChatMessage) => { + const dataId = data.id as string | undefined + const assistantId = + (data.assistant_message_id as string | undefined) || + currentAssistantMessageId.value || + undefined + + const matched = findLastMessage((item) => { + if (item.role !== 'assistant') return false + if (dataId && (item.request_id === dataId || item.id === dataId)) return true + if (assistantId && (item.id === assistantId || item.request_id === assistantId)) return true + return false + }) + if (matched) return matched + + return findLastMessage((item) => item.role === 'assistant' && !item.is_completed) + } + + const applyKnowledgeReferences = (data: ChatMessage) => { + const refs = extractKnowledgeReferences(data) + if (!refs.length) return undefined + + let message = resolveActiveAssistantMessage(data) + const created = !message + if (!message) { + const rowId = (data.id as string | undefined) || currentAssistantMessageId.value + message = { + id: rowId, + request_id: rowId, + role: 'assistant', + content: '', + showThink: false, + thinkContent: '', + thinking: false, + is_completed: false, + knowledge_references: [], + } + ensureAgentMessageShell(message, data.id as string | undefined) + messagesList.push(message) + onMessageCreated?.(message) + loading.value = false + } else { + ensureAgentMessageShell(message, data.id as string | undefined) + } + + message.knowledge_references = refs.slice() + if (created) onAgentChunkBound?.(message, true) + onMessageUpdated?.(message, data) + log('[References] Saved to message, count:', refs.length) + return message + } + const ensureAgentMessageShell = (message: ChatMessage, requestId?: string) => { message.isAgentMode = true + if (!isAgentStreamSession()) { + message.isRagMode = true + } if (!message.agentEventStream) message.agentEventStream = [] if (!message._eventMap) message._eventMap = new Map() if (!message._pendingToolCalls) message._pendingToolCalls = new Map() @@ -79,8 +146,44 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { const shouldRenderAssistantMessage = (session: ChatMessage) => { if (!session?.isAgentMode) return true + if (!session.is_completed) return true const stream = session.agentEventStream - return Array.isArray(stream) && stream.length > 0 + if (Array.isArray(stream) && stream.length > 0) return true + if (Array.isArray(session.knowledge_references) && session.knowledge_references.length > 0) { + return true + } + return false + } + + const shouldShowGlobalTypingIndicator = ( + messages: ChatMessage[], + isLoading: boolean, + isRecovering = false, + ) => { + if (!isLoading && !isRecovering) return false + const last = messages[messages.length - 1] + if (last?.role === 'assistant' && last?.isAgentMode && !last?.is_completed) { + return false + } + return true + } + + /** Quick-answer sessions: restore flags lost after history reload. */ + const restoreQuickAnswerFlags = (item: ChatMessage) => { + if (isAgentStreamSession() || item.role !== 'assistant') return + item.isRagMode = true + if ( + item.agent_steps && + Array.isArray(item.agent_steps) && + item.agent_steps.length > 0 + ) { + item.isAgentMode = true + item.hideContent = true + } + ensureRagPipelineHistoryStream(item as Parameters[0]) + if (item.isRagMode && item.agentEventStream) { + item.agentEventStream = markRaw(item.agentEventStream as object) + } } const recomposeAgentAnswer = (message: ChatMessage) => { @@ -233,6 +336,8 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { item.hideContent = true } + restoreQuickAnswerFlags(item) + if (item.content) { const content = String(item.content) const thinkCloseTag = '' @@ -329,6 +434,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { role: 'assistant', content: '', isAgentMode: true, + isRagMode: !isAgentStreamSession(), agentEventStream: [], _eventMap: new Map(), knowledge_references: [], @@ -575,14 +681,6 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { } break } - case 'references': { - if (dataPayload?.references) { - message.knowledge_references = dataPayload.references - } else if (data.knowledge_references) { - message.knowledge_references = data.knowledge_references - } - break - } case 'answer': { message.thinking = false const eventId = dataPayload?.event_id as string | undefined @@ -696,6 +794,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { role: 'assistant', content: '', isAgentMode: true, + isRagMode: !isAgentStreamSession(), is_completed: false, agentEventStream: [], _eventMap: new Map(), @@ -704,6 +803,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { } messagesList.push(existingMessage) onMessageCreated?.(existingMessage) + loading.value = false scrollToBottom(true) log('[Agent Query] Created agent placeholder message') } else { @@ -740,36 +840,8 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { isAgentCompleteChunk if (data.response_type === 'references') { - if (isCurrentlyAgentMode) { - handleAgentChunk(data) - return - } - let existingMessage = findLastMessage( - (item) => item.request_id === data.id || item.id === data.id, - ) - if (!existingMessage) { - existingMessage = { - id: data.id, - request_id: data.id, - role: 'assistant', - content: '', - showThink: false, - thinkContent: '', - thinking: false, - is_completed: false, - knowledge_references: [], - } - messagesList.push(existingMessage) - onMessageCreated?.(existingMessage) - loading.value = false - scrollToBottom(true) - } - const refs = - data.knowledge_references || - (data.data as ChatMessage | undefined)?.references || - [] - existingMessage.knowledge_references = refs - log('[References] Saved to message, count:', Array.isArray(refs) ? refs.length : 0) + applyKnowledgeReferences(data) + scrollToBottom() return } @@ -849,6 +921,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { return { findLastMessage, shouldRenderAssistantMessage, + shouldShowGlobalTypingIndicator, handleMsgList, processStreamChunk, } diff --git a/frontend/src/types/tool-results.ts b/frontend/src/types/tool-results.ts index a51640f3..ef1ce948 100644 --- a/frontend/src/types/tool-results.ts +++ b/frontend/src/types/tool-results.ts @@ -21,6 +21,7 @@ export type DisplayType = | 'web_search_results' | 'web_fetch_results' | 'grep_results' + | 'knowledge_chunks_list' | 'wiki_write_page' | 'wiki_replace_text' | 'wiki_rename_page' @@ -248,12 +249,27 @@ export interface GrepResultsData { chunk_results?: GrepChunkResult[]; knowledge_results: GrepKnowledgeResult[]; result_count: number; + document_count?: number; total_matches: number; knowledge_base_ids?: string[]; limit?: number; max_results: number; } +// Knowledge chunks list data (list_knowledge_chunks tool) +export interface KnowledgeChunksListData { + display_type: 'knowledge_chunks_list'; + knowledge_id?: string; + knowledge_title?: string; + total_chunks?: number; + fetched_chunks?: number; + page?: number; + page_size?: number; + faq_question?: string; + faq_id?: string; + single_chunk?: boolean; +} + // Wiki write page data export interface WikiWritePageData { display_type: 'wiki_write_page'; @@ -309,6 +325,7 @@ export type ToolResultData = | WebSearchResultsData | WebFetchResultsData | GrepResultsData + | KnowledgeChunksListData | WikiWritePageData | WikiReplaceTextData | WikiRenamePageData diff --git a/frontend/src/utils/agent-tool-display.test.mjs b/frontend/src/utils/agent-tool-display.test.mjs new file mode 100644 index 00000000..084eabbd --- /dev/null +++ b/frontend/src/utils/agent-tool-display.test.mjs @@ -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 2<\/strong> from 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 讯飞开放平台') +}) diff --git a/frontend/src/utils/agent-tool-display.ts b/frontend/src/utils/agent-tool-display.ts new file mode 100644 index 00000000..38111d63 --- /dev/null +++ b/frontend/src/utils/agent-tool-display.ts @@ -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 + + queries.push(...collectQueryStrings(record.query)) + queries.push(...collectQueryStrings(record.queries)) + + return Array.from(new Set(queries)).join(',') +} + +export function getKnowledgeSearchSummaryHtml( + t: ComposerTranslation, + toolData: Record | 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: `${count}`, + files: `${kbCount}`, + }) + } + + return t('agentStream.search.foundResults', { count: `${count}` }) +} + +type RagPipelineEvent = { + tool_name?: string + pending?: boolean + success?: boolean + arguments?: unknown + tool_data?: Record | 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 '' +} diff --git a/frontend/src/utils/agent-tool-icons.ts b/frontend/src/utils/agent-tool-icons.ts new file mode 100644 index 00000000..b2e1050c --- /dev/null +++ b/frontend/src/utils/agent-tool-icons.ts @@ -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' +} diff --git a/frontend/src/utils/grepResultsGroup.test.mjs b/frontend/src/utils/grepResultsGroup.test.mjs new file mode 100644 index 00000000..11f44088 --- /dev/null +++ b/frontend/src/utils/grepResultsGroup.test.mjs @@ -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, + ) +}) diff --git a/frontend/src/utils/grepResultsGroup.ts b/frontend/src/utils/grepResultsGroup.ts new file mode 100644 index 00000000..1f75f5ba --- /dev/null +++ b/frontend/src/utils/grepResultsGroup.ts @@ -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() + 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 +} diff --git a/frontend/src/utils/knowledgeChunksDisplay.test.mjs b/frontend/src/utils/knowledgeChunksDisplay.test.mjs new file mode 100644 index 00000000..cb0c15f5 --- /dev/null +++ b/frontend/src/utils/knowledgeChunksDisplay.test.mjs @@ -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 20<\/strong>\/282<\/strong>/) + assert.match(html, /page 3\/20/) +}) diff --git a/frontend/src/utils/knowledgeChunksDisplay.ts b/frontend/src/utils/knowledgeChunksDisplay.ts new file mode 100644 index 00000000..11fb24c5 --- /dev/null +++ b/frontend/src/utils/knowledgeChunksDisplay.ts @@ -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: `${toolData.fetched_chunks ?? 0}`, + total: `${toolData.total_chunks ?? '?'}`, + }), + ] + + 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(' · ') +} diff --git a/frontend/src/utils/rag-pipeline-history.test.mjs b/frontend/src/utils/rag-pipeline-history.test.mjs new file mode 100644 index 00000000..252210f2 --- /dev/null +++ b/frontend/src/utils/rag-pipeline-history.test.mjs @@ -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') +}) diff --git a/frontend/src/utils/rag-pipeline-history.ts b/frontend/src/utils/rag-pipeline-history.ts new file mode 100644 index 00000000..ac8e8904 --- /dev/null +++ b/frontend/src/utils/rag-pipeline-history.ts @@ -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> +} + +export function hasRagPipelineToolEvents(stream: Array> | 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> { + const refs = item.knowledge_references ?? [] + const kbCounts: Record = {} + + 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> = [ + { + 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 +} diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.style.test.mjs b/frontend/src/views/chat/components/AgentStreamDisplay.style.test.mjs new file mode 100644 index 00000000..8da3a7c1 --- /dev/null +++ b/frontend/src/views/chat/components/AgentStreamDisplay.style.test.mjs @@ -0,0 +1,80 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import test from 'node:test' + +const here = dirname(fileURLToPath(import.meta.url)) +const source = readFileSync(join(here, 'AgentStreamDisplay.vue'), 'utf8') + +test('agent steps use compact muted timeline styling', () => { + assert.match(source, /--agent-step-text-size:\s*14px/) + assert.match(source, /--agent-step-summary-size:\s*13px/) + assert.match(source, /--agent-step-icon-color:\s*var\(--td-text-color-placeholder\)/) + assert.match(source, /max-height:\s*none/) + assert.match(source, /overflow-y:\s*visible/) + assert.match(source, /\.tree-root \.action-name\s*\{[\s\S]*font-size:\s*14px/) + assert.match(source, /\.tree-child \.action-title-icon\s*\{[\s\S]*position:\s*absolute/) + assert.match(source, /function maskIconStyle\(src: string, size = 18\)/) + assert.match(source, /\.icon-mask\s*\{[\s\S]*background-color:\s*var\(--agent-step-icon-color\)/) + assert.doesNotMatch(source, /\.action-title \.action-title-icon,\s*\n\s*\.icon-mask\s*\{/) +}) + +test('expanded agent step log hides raw thinking narration', () => { + assert.match(source, /visibleIntermediateEvents\s*=\s*computed/) + assert.match(source, /e\.type === 'thinking'\)\s*return false/) + assert.match(source, /e\.type === 'tool_call' && e\.tool_name === 'thinking'\)\s*return false/) + assert.match(source, /v-for="\(event, index\) in visibleIntermediateEvents"/) +}) + +test('streaming log also hides raw thinking narration', () => { + assert.match(source, /if \(!isConversationDone\.value\)\s*\{\s*return result\.filter/) + assert.match(source, /e\.type === 'thinking'\) return false/) + assert.match(source, /e\.type === 'tool_call' && e\.tool_name === 'thinking'\) return false/) + assert.doesNotMatch(source, /if \(!isConversationDone\.value\)\s*\{\s*return result;\s*\}/) +}) + +test('streaming tool log uses the same timeline structure', () => { + assert.match(source, /'is-streaming-timeline': showStreamingTimeline/) + assert.match(source, /'tree-child': isStreamingTimelineEvent\(event\)/) + assert.match(source, /class="tree-child tree-child-last streaming-loading-node"/) + assert.match(source, /chat-timeline-loading\.less/) + assert.match(source, /lastStreamingTimelineEventIndex\s*=\s*computed/) +}) + +test('final done row uses an existing common translation key', () => { + assert.match(source, /t\('common\.finish'\)/) + assert.doesNotMatch(source, /\$t\('common\.done'\)/) + assert.match(source, /'tree-child-last': !isConversationDone && index === visibleIntermediateEvents\.length - 1/) +}) + +test('tool rows use line icon names instead of legacy asset masks', () => { + assert.match(source, /getAgentToolIconName/) + assert.match(source, /:name="getToolIconName\(event\.tool_name\)"/) + assert.match(source, /wiki_read_source_doc: 'agentStream\.tools\.wikiReadSourceDoc'/) + assert.match(source, /toolName === 'get_document_content' \|\| toolName === 'wiki_read_source_doc'/) + assert.doesNotMatch(source, /getToolIcon\(event\.tool_name\)/) +}) + +test('rag mode delegates pre-answer loading to pipeline and keeps dots while answer streams', () => { + assert.match(source, /if \(props\.ragMode\) return hasAnswerStarted\.value/) + assert.match(source, /v-if="!ragMode \|\| displayEvents\.length > 0 \|\| showAgentActivityIndicator"/) +}) + +test('only the collapsed root summary shows an expand chevron', () => { + assert.match(source, /tree-root-summary[\s\S]*class="action-show-icon"/) + assert.match(source, /showIntermediateSteps \? 'chevron-down' : 'chevron-right'/) + assert.doesNotMatch(source, /isEventExpanded\(event\.tool_call_id\) \? 'chevron/) + assert.doesNotMatch(source, /isEventExpanded\(event\.event_id\) \? 'chevron/) +}) + +test('pending tool rows do not render an extra axis dot', () => { + assert.doesNotMatch(source, /&\.action-pending\s*\{[\s\S]*&::after/) +}) + +test('agent mode keeps gray timeline dots for the full turn', () => { + assert.match(source, /if \(isConversationDone\.value\) return false/) + assert.match(source, /if \(props\.ragMode\) return false/) + assert.match(source, /return true;\s*\}\);/) + assert.match(source, /chat-timeline-loading\.less/) +}) diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue index c2cef927..25cd3977 100644 --- a/frontend/src/views/chat/components/AgentStreamDisplay.vue +++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue @@ -1,21 +1,26 @@