chore: 项目基线(基于 WeKnora 定制版,整理文件忽略规则)

This commit is contained in:
runny committed 2026-11-13 17:54:56 +08:00
commit 9097ee699d
5769 files changed
+1446466

No files matched your search

@@ -0,0 +1,70 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { runInNewContext } from 'node:vm'
import test from 'node:test'
import { compileTemplate } from '@vue/compiler-sfc'
import * as vue from 'vue'
import ts from 'typescript'
const source = readFileSync(new URL('./index.vue', import.meta.url), 'utf8')
const start = source.indexOf('<div class="input-container"')
const end = source.indexOf('</InputField>', start) + '</InputField>'.length
const compiled = compileTemplate({
source: `${source.slice(start, end)}</div>`, filename: 'index.vue', id: 'automation-composer',
})
assert.deepEqual(compiled.errors, [])
const exports: any = {}
runInNewContext(ts.transpileModule(compiled.code, {
compilerOptions: { module: ts.ModuleKind.CommonJS },
}).outputText, {
exports, require: () => ({
...vue, resolveComponent: (name: string) => name, withCtx: (fn: unknown) => fn,
withDirectives: (node: unknown) => node,
}),
})
function nodes(node: any): any[] {
if (!node || typeof node !== 'object') return []
if (Array.isArray(node)) return node.flatMap(nodes)
const children = node.children
return [node, ...(Array.isArray(children) ? nodes(children)
: children && typeof children === 'object'
? Object.values(children).flatMap(slot => typeof slot === 'function' ? nodes(slot()) : []) : [])]
}
function render(kind: string | null, embeddedMode = false) {
const currentSession = vue.ref(kind === null ? null : { kind })
const declaration = source.match(/const isAutomationSession = .*;/)![0]
const isAutomationSession = runInNewContext(`${declaration}\nisAutomationSession`, { currentSession, computed: vue.computed })
return nodes(exports.render({
currentSession: currentSession.value, isAutomationSession: isAutomationSession.value,
embeddedMode, userHasScrolledUp: false, onClickScrollToBottom() {}, t: (key: string) => key,
focusComposerOnMount: false, isReplying: false, composerLocked: false, session_id: 'session',
currentAssistantMessageId: '', modelId: '', defaultModelId: '', steerQueue: [],
isAgentStreamSession: () => true, $slots: {}, backgroundItems: [],
}, []))
}
test('automation conversations replace the composer with a notice but retain prompt responses', () => {
const rendered = render('automation')
assert.ok(rendered.some(node => node.props?.class === 'automation-session-notice'))
assert.ok(rendered.some(node => node.type === 'PendingPromptDock'))
assert.ok(!rendered.some(node => node.type === 'InputField'))
})
test('normal and embedded conversations keep their composer, while unknown sessions wait for metadata', () => {
assert.ok(render('chat').some(node => node.type === 'InputField'))
assert.ok(render(null, true).some(node => node.type === 'InputField'))
assert.ok(!render(null).some(node => node.type === 'InputField'))
})
test('automation history does not offer fork or rewind actions that lead back to a composer', () => {
const fork = source.slice(source.indexOf('function forkAffordanceOf('), source.indexOf('// One pass over the transcript'))
const rewind = source.slice(source.indexOf('function canRewindMessage('), source.indexOf('const FORK_PREFILL_KEY'))
for (const automation of [true, false]) {
const actions = runInNewContext(`${fork}\n${rewind}\n({ forkAffordanceOf, canRewindMessage })`, {
isAutomationSession: { value: automation }, messagesList: [],
rewindableIds: { value: new Set(['message']) }, resolveForkAffordance: () => ({ canFork: true }),
})
assert.equal(actions.forkAffordanceOf('message').canFork, !automation)
assert.equal(actions.canRewindMessage('message'), !automation)
}
})
@@ -0,0 +1,40 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { runInNewContext } from 'node:vm'
import test from 'node:test'
import { createBackgroundWorkPoller } from '../../utils/backgroundWork.ts'
test('chat page retries its first failed background query and stops after a confirmed empty list', async (t) => {
const source = readFileSync(new URL('./index.vue', import.meta.url), 'utf8')
const start = source.indexOf('const backgroundPoller = createBackgroundWorkPoller(')
const end = source.indexOf('\nfunction startBackgroundWork()', start)
assert.ok(start >= 0 && end > start)
t.mock.timers.enable({ apis: ['setTimeout'] })
let calls = 0
const backgroundItems = { value: [] as any[] }
const running = [{ work_id: 'sj_0123', kind: 'shell', title: 'build', state: 'running' }]
const poller = runInNewContext(`${source.slice(start, end)}\nbackgroundPoller`, {
session_id: { value: 's' }, backgroundItems,
createBackgroundWorkPoller: (options: Parameters<typeof createBackgroundWorkPoller>[0]) =>
createBackgroundWorkPoller({ ...options, intervalMs: 10 }),
listBackgroundWork: async () => {
calls++
if (calls === 1) throw new Error('HTTP 503')
return calls === 2 ? running : []
},
replaceBackgroundItems: (items: any[]) => { backgroundItems.value = items },
})
try {
poller.start()
await Promise.resolve()
t.mock.timers.tick(10)
await Promise.resolve()
assert.equal(calls, 2, 'the real page callback must not stop retries while its initial list is empty')
assert.deepEqual(backgroundItems.value, running)
t.mock.timers.tick(10)
await Promise.resolve()
assert.deepEqual(backgroundItems.value, [])
t.mock.timers.tick(100)
assert.equal(calls, 3, 'a successful empty response ends polling')
} finally { poller.dispose() }
})
@@ -0,0 +1,104 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import vm from 'node:vm'
import ts from 'typescript'
import { parse } from '@vue/compiler-sfc'
import { computed, reactive, ref } from 'vue'
import { persistedAssistantId } from '../../../utils/steerStreamFork.ts'
const source = readFileSync(new URL('./AgentStreamDisplay.vue', import.meta.url), 'utf8')
const child = parse(readFileSync(new URL('./ChildAgentStream.vue', import.meta.url), 'utf8')).descriptor
const start = source.indexOf('const showArtifactDrawer = ')
const end = source.indexOf('\nconst artifactRefContext = ', start)
assert.ok(start >= 0 && end > start)
const code = ts.transpile(source.slice(start, end))
function setup(overrides = {}, withPanel = true) {
const calls = []
const props = reactive({
sessionId: 'child-session',
session: { id: 'child-message', artifacts: [
{ file_name: 'deleted.md', deleted_at: '2026-10-18' },
{ file_name: 'slides.pptx' },
{ file_name: 'notes.md' },
] },
...overrides,
})
const state = vm.runInNewContext(`${code}; ({
openArtifactDrawer, showArtifactDrawer, artifactPreviewIndex, useArtifactDrawer,
sessionIdForArtifacts, messageIdForArtifacts, liveArtifacts,
})`, {
props, computed, ref,
useChatSandboxPanel: () => withPanel ? {
toggleArtifacts: id => calls.push(['toggle', id]),
open: (tab, focus) => calls.push(['open', tab, focus.messageId, focus.previewIndex]),
} : null,
persistedAssistantId,
useArtifactArriveMotion: () => ({}),
isCollectingSkillArtifacts: () => false,
})
return { ...state, props, calls }
}
test('child viewer explicitly routes artifacts locally while retaining the child session', () => {
const stream = child.template.ast.children[0].children[0].children
.find(node => node.tag === 'template').children.find(node => node.tag === 'AgentStreamDisplay')
assert.ok(stream.props.some(prop => prop.type === 6 && prop.name === 'artifacts-in-drawer'))
assert.ok(stream.props.some(prop => prop.arg?.content === 'session-id' && prop.exp?.content === 'task.sessionId'))
// Rendering and click routing must agree; otherwise clicks only toggle invisible state.
const drawer = parse(source).descriptor.template.ast.children.find(node => node.tag === 'ChatArtifactsDrawer')
for (const [attribute, expression] of [
['session-id', 'sessionIdForArtifacts'], ['message-id', 'messageIdForArtifacts'],
['artifacts', 'liveArtifacts'], ['preview-index', 'artifactPreviewIndex'],
]) {
assert.ok(drawer.props.some(prop => prop.arg?.content === attribute && prop.exp?.content === expression))
}
const condition = drawer.props.find(prop => prop.name === 'if').exp.content
const ctx = setup({ artifactsInDrawer: true })
assert.equal(vm.runInNewContext(condition, {
hasArtifacts: true, embeddedMode: false, useArtifactDrawer: ctx.useArtifactDrawer.value,
sessionIdForArtifacts: ctx.sessionIdForArtifacts.value,
messageIdForArtifacts: ctx.messageIdForArtifacts.value,
}), 'child-message')
})
test('child inline cards and folder use the same local drawer, preserving original file indexes', () => {
const ctx = setup({ artifactsInDrawer: true })
for (const index of [1, 2]) {
ctx.openArtifactDrawer(index)
assert.equal(ctx.showArtifactDrawer.value, true)
assert.equal(ctx.artifactPreviewIndex.value, index)
assert.equal(ctx.liveArtifacts.value.find(file => file.index === index).file_name,
index === 1 ? 'slides.pptx' : 'notes.md')
assert.equal(ctx.sessionIdForArtifacts.value, 'child-session')
assert.equal(ctx.messageIdForArtifacts.value, 'child-message')
ctx.showArtifactDrawer.value = false
}
ctx.openArtifactDrawer()
assert.equal(ctx.showArtifactDrawer.value, true)
assert.equal(ctx.artifactPreviewIndex.value, null)
assert.deepEqual(ctx.calls, [], 'must not send child message IDs to the parent panel')
})
test('main conversation retains panel routing; embedded and standalone viewers have a visible fallback', () => {
const main = setup({ sessionId: 'main-session', session: { id: 'main-message', artifacts: [{}] } })
main.openArtifactDrawer()
main.openArtifactDrawer(0)
assert.equal(main.useArtifactDrawer.value, false)
assert.equal(main.showArtifactDrawer.value, false)
assert.deepEqual(main.calls, [['toggle', 'main-message'], ['open', 'artifacts', 'main-message', 0]])
for (const ctx of [setup({ embeddedMode: true }), setup({}, false)]) {
ctx.openArtifactDrawer(1)
assert.equal(ctx.useArtifactDrawer.value, true)
assert.equal(ctx.showArtifactDrawer.value, true)
assert.deepEqual(ctx.calls, [])
}
})
test('messages without live artifacts do not open either surface', () => {
const ctx = setup({ artifactsInDrawer: true, session: { id: 'empty', artifacts: [] } })
ctx.openArtifactDrawer()
assert.equal(ctx.showArtifactDrawer.value, false)
assert.deepEqual(ctx.calls, [])
})
@@ -0,0 +1,110 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { test } from 'node:test'
import vm from 'node:vm'
import ts from 'typescript'
import { computed, ref } from 'vue'
import { useDeferredTimelineCompletion } from '../../../composables/useChatScrollFollow'
import { foldProgressIntoThinking } from '../../../utils/agentTimelinePresentation'
const source = readFileSync(new URL('./AgentStreamDisplay.vue', import.meta.url), 'utf8')
test('delegated work keeps progress and approvals in one chronological stream and restores the completed steps fold without duplicating child entry points', () => {
const collapse = source.slice(source.indexOf('const shouldShowCollapsedSteps ='), source.indexOf('// Once the steps collapse'))
const display = source.slice(source.indexOf('const displayEvents ='), source.indexOf('const isPageLinkEvent ='))
const done = ref(false)
const delegated = ref(false)
const expanded = ref(false)
const readingHistory = ref(false)
const stream = ref<any[]>([
{ type: 'thinking', event_id: 'r1', content: 'Check agents' },
{ type: 'progress', event_id: 'p1', content: '两个智能体已经并行开工了。' },
{ type: 'tool_approval_required', pending_id: 'approval', resolved: false },
])
const code = ts.transpileModule(`${collapse}\n${display}\n({ shouldShowCollapsedSteps, displayEvents })`, {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
}).outputText
const state = vm.runInNewContext(code, {
computed, props: { ragMode: false }, hasCollaborationTasks: delegated, showIntermediateSteps: expanded,
eventStream: stream, isConversationDone: done, intermediateStepsCount: ref(2), readingHistory, timelineCompleted: useDeferredTimelineCompletion(done, readingHistory),
buildFullEventList: foldProgressIntoThinking, finalContent: ref(null),
})
for (const hasChildren of [false, true]) {
delegated.value = hasChildren
assert.equal(state.shouldShowCollapsedSteps.value, false)
assert.deepEqual(Array.from(state.displayEvents.value, (e: any) => e.type), ['thinking', 'tool_approval_required'])
assert.equal(state.displayEvents.value[0].title, '两个智能体已经并行开工了。')
assert.equal(state.displayEvents.value[1].resolved, false)
}
stream.value[2].resolved = true
assert.equal(state.displayEvents.value[1].resolved, true)
stream.value.push({ type: 'answer', content: '完整结果' })
stream.value.splice(2, 0, { type: 'child_task', event_id: 'child-a', task: { id: 'a' } })
readingHistory.value = true
done.value = true
assert.equal(state.shouldShowCollapsedSteps.value, false, 'completion must not fold history under the reader')
assert.ok(state.displayEvents.value.some((event: any) => event.type === 'thinking'))
readingHistory.value = false
assert.equal(state.shouldShowCollapsedSteps.value, true)
assert.deepEqual(Array.from(state.displayEvents.value, (e: any) => e.type), ['answer'])
readingHistory.value = true
assert.equal(state.shouldShowCollapsedSteps.value, true, 'older completed timelines stay folded when reading history')
readingHistory.value = false
expanded.value = true
assert.deepEqual(Array.from(state.displayEvents.value, (e: any) => e.type), ['answer'])
expanded.value = false
stream.value = stream.value.filter(e => e.type !== 'answer')
assert.equal(state.displayEvents.value.length, 0)
expanded.value = true
assert.equal(state.displayEvents.value.length, 0)
stream.value = [{ type: 'answer', content: '完整结果' }]
delegated.value = false
assert.equal(state.shouldShowCollapsedSteps.value, true)
assert.deepEqual(Array.from(state.displayEvents.value, (e: any) => e.content), ['完整结果'])
})
test('the template has no second latest-progress outlet above the timeline', () => {
assert.doesNotMatch(source, /CollaborationProgress|latestParentProgress/)
})
test('live child waiting uses the timeline tail icon and existing pending shimmer', () => {
const template = source.slice(0, source.indexOf('</template>\n\n<script'))
const tail = template.slice(template.indexOf('<!-- One live tail node'), template.indexOf('<!-- 引用 hover'))
assert.match(tail, /v-if="showAgentActivityIndicator \|\| childActivity"/)
assert.match(tail, /class="tree-child tree-child-last streaming-loading-node"/)
assert.match(tail, /role="status" aria-live="polite"/)
assert.match(tail, /class="action-card action-pending"/)
assert.match(tail, /<ChatTimelineIcon class="action-title-icon" name="lightbulb"/)
assert.match(tail, /class="action-name"/)
assert.match(template, /!showAgentActivityIndicator && !childActivity && index === lastStreamingTimelineEventIndex/)
assert.doesNotMatch(template, /agent-child-activity|child-wait-spinner|child_wait/)
})
test('thinking resumes after child waiting and resolved approval', () => {
const snippet = source.slice(source.indexOf('const hasPendingStreamingActivity ='), source.indexOf('const isStreamingTimelineEvent ='))
const events = ref<any[]>([]), done = ref(false), wait = ref('finished'), answering = ref(false)
const code = ts.transpileModule(`${snippet}\n({ showAgentActivityIndicator })`, {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
}).outputText
const state = vm.runInNewContext(code, {
computed, displayEvents: events, isSegmentDone: done, hasCollaborationTasks: ref(true),
props: { ragMode: false }, hasAnswerStarted: answering, collaborationWait: wait,
isThinkingActive: () => false,
isUnresolvedCollaborationPrompt: (event: any) => event.type === 'tool_approval_required' && !event.resolved,
})
assert.equal(state.showAgentActivityIndicator.value, true)
events.value = [{ type: 'tool_approval_required', resolved: true }]
assert.equal(state.showAgentActivityIndicator.value, true)
events.value[0].resolved = false
assert.equal(state.showAgentActivityIndicator.value, false)
events.value = []
wait.value = 'waiting'
assert.equal(state.showAgentActivityIndicator.value, false)
wait.value = 'finished'
answering.value = true
assert.equal(state.showAgentActivityIndicator.value, false)
answering.value = false
done.value = true
assert.equal(state.showAgentActivityIndicator.value, false)
})
@@ -0,0 +1,167 @@
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'
import vm from 'node:vm'
import { computed, reactive, ref } from 'vue'
import { isAssistantTurnComplete } from '../../../utils/steerStreamFork.ts'
import { useDeferredTimelineCompletion } from '../../../composables/useChatScrollFollow.ts'
import { collaborationWaitState, collaborationActivity } from '../../../utils/collaborationDisplay.ts'
const here = dirname(fileURLToPath(import.meta.url))
const source = readFileSync(join(here, 'AgentStreamDisplay.vue'), 'utf8')
test('streamed responses do not mount a hidden Wiki drawer that steals composer focus', () => {
assert.match(source, /<t-drawer v-if="wikiDrawerVisible" v-model:visible="wikiDrawerVisible"/)
})
test('steer seals animation while keeping the preceding timeline open without completion', () => {
const stateBlock = source.slice(source.indexOf('const isConversationDone ='), source.indexOf('const streamingMermaidSvgCache ='))
const collapseBlock = source.slice(source.indexOf('const shouldShowCollapsedSteps ='), source.indexOf('// Once the steps collapse'))
const props = reactive({ ragMode: false, session: { steerForked: true, is_completed: true } })
const state = vm.runInNewContext(`${stateBlock}\n${collapseBlock}\n({ isConversationDone, isSegmentDone, shouldShowCollapsedSteps })`, {
props, computed, isAssistantTurnComplete, intermediateStepsCount: { value: 2 },
useDeferredTimelineCompletion, readingHistory: ref(false), eventStream: ref([]),
collaborationWaitState, collaborationActivity,
isAwaitingInput: (m) => m?.run_state === 'awaiting_input',
})
assert.equal(state.isSegmentDone.value, true)
assert.equal(state.isConversationDone.value, false)
assert.equal(state.shouldShowCollapsedSteps.value, false)
props.session.steerForked = false
assert.equal(state.isConversationDone.value, true)
assert.equal(state.shouldShowCollapsedSteps.value, true)
props.session.run_state = 'awaiting_input'
assert.equal(state.isConversationDone.value, false)
assert.equal(state.shouldShowCollapsedSteps.value, false)
})
test('agent steps use compact muted timeline styling', () => {
const theme = readFileSync(join(here, '../../../components/css/chat-timeline-theme.less'), 'utf8')
assert.match(source, /\.chat-timeline-theme\(\)/)
assert.match(theme, /--agent-step-text-size:\s*14px/)
assert.match(theme, /--agent-step-summary-size:\s*13px/)
assert.match(theme, /--agent-step-icon-color:\s*var\(--agent-step-color\)/)
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|var\(--app-text-base\))/)
assert.match(source, /\.tree-child \.action-title-icon\s*\{[\s\S]*position:\s*absolute/)
assert.doesNotMatch(source, /maskIconStyle|icon-mask|<BrowserIcon/)
assert.match(source, /<ChatTimelineIcon v-if="event.tool_name"/)
})
test('expanded agent step log keeps model thinking in the tool timeline', () => {
assert.match(source, /visibleIntermediateEvents\s*=\s*computed\(\(\) => attachReasoningToTools\(intermediateEvents\.value, canAttachReasoning\)\)/)
assert.match(source, /v-for="\(event, index\) in timelineEvents"/)
assert.match(source, /class="action-reasoning thinking-detail-content markdown-content"/)
assert.match(source, /v-for="\(event, index\) in visibleIntermediateEvents"/)
})
test('streaming log renders reasoning alongside tool calls', () => {
assert.match(source, /if \(!timelineCompleted\.value\)\s*\{\s*return result;\s*\}/)
})
test('expanded model reasoning stays inline without a separate thinking title', () => {
assert.match(source, /class="thinking-inline-content markdown-content"/)
assert.match(source, /class="thinking-inline-markdown" v-html="renderMarkdownContent\(event\.content\)"/)
assert.match(source, /event\.title && event\.content && isEventExpanded\(event\.event_id\)/)
assert.match(source, /\.thinking-inline-title\s*\{[\s\S]*align-items:\s*flex-start/)
assert.match(source, /\.thinking-inline-content\s*\{[\s\S]*margin-top:\s*0/)
assert.doesNotMatch(source, /\.thinking-inline-title > \.action-title-icon/)
assert.match(source, /\.tree-child \.thinking-event-card \.action-title\s*\{[\s\S]*position:\s*static/)
})
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\(wasUserStopped \? 'input\.messages\.stopSuccess' : 'common\.finish'\)/)
assert.doesNotMatch(source, /\$t\('common\.done'\)/)
assert.match(source, /'tree-child-last': !isSegmentDone && 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_search: 'agentEditor\.tools\.wikiSearch'/)
assert.match(source, /wiki_read_page: 'agentEditor\.tools\.wikiReadPage'/)
assert.match(source, /wiki_read_source_doc: 'agentStream\.tools\.wikiReadSourceDoc'/)
assert.match(source, /list_sandbox_files: 'agentStream\.tools\.listSandboxFiles'/)
assert.match(source, /read_sandbox_file: 'agentStream\.tools\.readSandboxFile'/)
assert.match(source, /write_sandbox_file: 'agentStream\.tools\.writeSandboxFile'/)
assert.match(source, /edit_sandbox_file: 'agentStream\.tools\.editSandboxFile'/)
assert.match(source, /getReadSkillTarget/)
assert.match(source, /tool_name === 'list_sandbox_files'/)
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 adds no row after answer starts', () => {
assert.match(source, /if \(props\.ragMode \|\| hasAnswerStarted\.value\) return false/)
assert.match(source, /v-if="displayEvents\.length > 0 \|\| showMemoryRow \|\| showAgentActivityIndicator \|\| childActivity"/)
assert.doesNotMatch(source, /ChatActivityIndicator/)
})
test('rag mode keeps model thinking out of the answer stream component', () => {
const displayEventsBlock = source.slice(
source.indexOf('const displayEvents = computed'),
source.indexOf('// Get unique key for event'),
)
assert.match(displayEventsBlock, /if \(props\.ragMode\)\s*\{[\s\S]*e\.type === 'answer'/)
assert.doesNotMatch(
displayEventsBlock,
/attachment_parsing/,
)
assert.doesNotMatch(
displayEventsBlock,
/if \(props\.ragMode\)\s*\{[\s\S]*e\.type === 'answer' \|\| e\.type === 'thinking'/,
)
})
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/)
})
// Recalled memory is one more thing the turn did before answering, so it rides
// the same timeline as the steps instead of sitting in a card above them. It has
// to travel into the collapsed tree with them, and appear exactly once.
test('recalled memory rides the agent timeline as its leading row', () => {
const template = source.split('<script')[0]
assert.equal((template.match(/<ChatMemoryStep/g) || []).length, 2)
assert.match(template, /<div v-if="showIntermediateSteps" class="tree-children">\s*\n\s*<ChatMemoryStep/)
assert.match(template, /<ChatMemoryStep\s*\n\s*v-if="showMemoryRow"/)
assert.match(template, /<ChatMemoryStep[\s\S]*?:is-last="memoryIsLast"/)
assert.match(source, /!props\.ragMode && hasMemory\.value && !shouldShowCollapsedSteps\.value/)
assert.match(
source,
/const memoryIsLast = computed\([\s\S]*lastStreamingTimelineEventIndex\.value === -1/,
)
})
test('pending tool rows do not render an extra axis dot', () => {
assert.doesNotMatch(source, /&\.action-pending\s*\{[\s\S]*&::after/)
})
test('agent mode shows a native placeholder before answer whenever nothing is pending', () => {
assert.match(source, /if \(isSegmentDone\.value\) return false/)
assert.match(source, /return !hasPendingStreamingActivity\.value/)
assert.match(source, /const hasPendingStreamingActivity = computed/)
assert.match(source, /event\.thinking === true \|\| isThinkingActive\(event\.event_id\)/)
assert.match(
source,
/return isUnresolvedCollaborationPrompt\(event\)/,
)
assert.match(source, /class="action-card action-pending"/)
assert.match(source, /childActivity \? 'agentStream\.collaboration\.waiting' : 'chat\.thinkingAlt'/)
assert.match(source, /chat-timeline-loading\.less/)
})
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,28 @@
<template>
<span class="artifact-file-icon" aria-hidden="true" v-html="iconSvg" />
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { renderArtifactFileIcon } from '@/utils/artifactFileIcon'
const props = defineProps<{ fileName: string }>()
const iconSvg = computed(() => renderArtifactFileIcon(props.fileName))
</script>
<style scoped lang="less">
@import '@/components/css/artifact-file-icon.less';
.artifact-file-icon {
display: inline-flex;
flex-shrink: 0;
width: 32px;
height: 38px;
:deep(.artifact-file-icon-svg) {
.artifact-file-icon-style();
width: 100%;
height: 100%;
}
}
</style>
@@ -0,0 +1,423 @@
<template>
<div v-if="interactive" class="prompt-panel" @click.stop>
<div class="prompt-question">{{ question.question }}</div>
<div v-if="options.length" class="prompt-options" role="listbox" :aria-multiselectable="multiSelect">
<button v-for="(option, index) in options" :key="option" type="button" role="option" class="prompt-option"
:class="{ 'is-selected': isSelected(option) }" :aria-selected="isSelected(option)" :disabled="submitting"
@click="toggleOption(option)">
<span class="prompt-option-key">{{ optionKey(index) }}</span>
<span class="prompt-option-label">{{ option }}</span>
<t-icon v-if="isSelected(option)" class="prompt-option-check" name="check" />
</button>
</div>
<div v-for="field in fields" :key="field.name" class="ask-field">
<label :id="`${pendingId}-${field.name}-label`" class="ask-field-label">
{{ field.label || field.name }}<span v-if="field.required" class="ask-required">*</span>
</label>
<t-input-number v-if="field.type === 'number'" v-model="values[field.name]" :disabled="submitting"
theme="normal" size="small" class="ask-number" />
<div v-else-if="field.type === 'multiselect'" class="ask-field-options" role="group"
:aria-labelledby="`${pendingId}-${field.name}-label`">
<label v-for="option in field.options || []" :key="option" class="ask-field-option"
:class="{ 'is-selected': fieldHasOption(field.name, option), 'is-disabled': submitting }">
<input type="checkbox" :checked="fieldHasOption(field.name, option)" :disabled="submitting"
@change="toggleFieldOption(field.name, option)" />
<span class="ask-field-option-mark" aria-hidden="true"><CheckIcon size="12px" /></span>
<span class="ask-field-option-text">{{ option }}</span>
</label>
</div>
<t-select v-else-if="field.type === 'select'" v-model="values[field.name]"
:disabled="submitting" size="small" clearable
:popup-props="{ overlayClassName: 'wk-popover' }"
:placeholder="$t('agentStream.askUser.selectPlaceholder')">
<t-option v-for="option in field.options || []" :key="option" :value="option" :label="option" />
</t-select>
<t-input v-else v-model="values[field.name]" :disabled="submitting" size="small" :maxlength="maxTextLen" />
</div>
<t-textarea v-if="acceptsText" v-model="text" class="ask-text" :disabled="submitting" :maxlength="maxTextLen"
:autosize="{ minRows: 1, maxRows: 6 }"
:placeholder="freeTextOnly ? $t('agentStream.askUser.textPlaceholder') : $t('agentStream.askUser.otherPlaceholder')" />
<div class="prompt-footer">
<div class="prompt-footer-meta">
<span v-if="parked" class="action-timer">{{ parkedText }}</span>
<span v-else-if="secondsLeft >= 0" class="action-timer" :class="timerClass">{{ countdownText }}</span>
</div>
<div class="prompt-footer-actions">
<button type="button" class="prompt-btn" :disabled="submitting" @click="submit(true)">
{{ $t('agentStream.askUser.decline') }}
</button>
<button type="button" class="prompt-btn is-primary" :disabled="submitting || !canSubmit" @click="submit(false)">
{{ $t('agentStream.askUser.submit') }}<span class="prompt-btn-key" aria-hidden="true">↵</span>
</button>
</div>
</div>
</div>
<div v-else class="action-card interaction-inline ask-inline" :class="{ 'action-pending': open }">
<div class="action-header no-results">
<div class="action-title">
<ChatTimelineIcon class="action-title-icon" :name="headerIcon" :active="open" />
<span class="action-name">{{ $t('agentStream.askUser.title') }}</span>
<span class="ask-status" role="status">
{{ awaitingInDock ? $t('agentStream.promptDock.waiting') : statusLine }}
</span>
<button v-if="awaitingInDock" type="button" class="inline-action is-primary" @click.stop="dock?.focus(pendingId)">
{{ $t('agentStream.promptDock.handle') }}
</button>
</div>
</div>
<div class="ask-question">{{ question.question }}</div>
<div v-if="answerSummary" class="ask-answer">
<span class="ask-answer-label">{{ $t('agentStream.askUser.answerLabel') }}</span>
<div class="ask-answer-text">{{ answerSummary }}</div>
</div>
</div>
</template>
<script setup lang="ts">
import ChatTimelineIcon from '@/components/ChatTimelineIcon.vue'
import { computed, inject, reactive, ref } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { CheckIcon } from 'tdesign-icons-vue-next'
import { useI18n } from 'vue-i18n'
import { resolveAgentPrompt } from '@/api/mcp-service'
import { resolveEmbedAgentPrompt } from '@/api/embed'
import { resumeSuspendedRunKey } from '@/utils/suspendedRun'
import { usePromptCountdown } from '@/composables/usePromptCountdown'
import { markPromptSubmitted, promptSubmission, usePromptDock } from '@/composables/usePromptDock'
import { buildAskUserResponse, canSubmitAskUser, summarizeAskUserAnswer, type AskUserQuestion } from '@/utils/askUser'
import { isSubmitKey, isTextEntry, optionIndexForKey, optionKey } from '@/utils/promptKeys'
const props = defineProps<{
pendingId: string
// dock: the answer form, shown above the composer. inline: the timeline row.
variant?: 'dock' | 'inline'
request?: AskUserQuestion
timeoutSeconds?: number
hotWaitSeconds?: number
suspendable?: boolean
suspended?: boolean
expiresAt?: string
requestedAt?: number
resolved?: boolean
answered?: boolean
response?: Record<string, unknown>
resolveReason?: string
timedOut?: boolean
canceled?: boolean
abandoned?: boolean
embeddedMode?: boolean
embedChannelId?: string
embedToken?: string
embedSessionId?: string
embedSessionSig?: string
embedVisitorId?: string
}>()
const { t } = useI18n()
const resumeSuspendedRun = inject(resumeSuspendedRunKey, undefined)
const dock = usePromptDock()
const { parked, secondsLeft, timerClass, countdownText, parkedText } = usePromptCountdown(props)
const maxTextLen = 4000
const question = computed<AskUserQuestion>(() => props.request || { question: '' })
const options = computed(() => question.value.options || [])
const fields = computed(() => question.value.fields || [])
const multiSelect = computed(() => Boolean(question.value.multi_select))
const freeTextOnly = computed(() => !options.value.length && !fields.value.length)
const acceptsText = computed(() => freeTextOnly.value || Boolean(question.value.allow_free_text))
const submission = computed(() => promptSubmission(props.pendingId))
const open = computed(() => !props.resolved && !submission.value)
// Without a dock (a view that does not provide one) the row stays answerable.
const interactive = computed(() => open.value && (props.variant === 'dock' || !dock))
const awaitingInDock = computed(() => open.value && props.variant !== 'dock' && Boolean(dock?.isDocked(props.pendingId)))
const selectedOne = ref('')
const selectedMany = ref<string[]>([])
const values = reactive<Record<string, unknown>>({})
const text = ref('')
const submitting = ref(false)
const fieldHasOption = (name: string, option: string) =>
Array.isArray(values[name]) && (values[name] as string[]).includes(option)
const toggleFieldOption = (name: string, option: string) => {
if (submitting.value) return
const selected = Array.isArray(values[name]) ? values[name] as string[] : []
values[name] = selected.includes(option)
? selected.filter(value => value !== option)
: [...selected, option]
}
const isSelected = (option: string) =>
multiSelect.value ? selectedMany.value.includes(option) : selectedOne.value === option
const toggleOption = (option: string) => {
if (submitting.value) return
if (!multiSelect.value) {
selectedOne.value = selectedOne.value === option ? '' : option
return
}
selectedMany.value = selectedMany.value.includes(option)
? selectedMany.value.filter((o) => o !== option)
: [...selectedMany.value, option]
}
const draft = () => buildAskUserResponse(question.value, {
selected: multiSelect.value ? selectedMany.value : (selectedOne.value ? [selectedOne.value] : []),
values,
text: text.value,
})
const canSubmit = computed(() => canSubmitAskUser(question.value, draft()))
const headerIcon = computed(() => {
if (!props.resolved) return 'help-circle'
return props.answered ? 'check-circle' : 'minus-circle'
})
const statusLine = computed(() => {
if (!props.resolved) {
if (submission.value?.declined) return t('agentStream.askUser.declinedTag')
if (submission.value) return t('agentStream.askUser.submitted')
return t('agentStream.askUser.unansweredTag')
}
if (props.abandoned) return t('agentStream.toolApproval.abandonedTag')
if (props.answered) return t('agentStream.askUser.answeredTag')
if (props.timedOut) return t('agentStream.askUser.timedOutTag')
if (props.canceled) return t('agentStream.askUser.canceledTag')
if (props.resolveReason?.includes('declined')) return t('agentStream.askUser.declinedTag')
return t('agentStream.askUser.unansweredTag')
})
const answerSummary = computed(() => {
const answer = props.resolved ? props.response : submission.value
if (!answer || answer.declined) return ''
return summarizeAskUserAnswer(question.value, answer)
})
const embedTarget = () =>
props.embeddedMode && props.embedChannelId && props.embedToken && props.embedSessionId
&& props.embedSessionSig && props.embedVisitorId
const submit = async (decline: boolean) => {
if (!open.value || submitting.value) return
if (!decline && !canSubmit.value) return
const response = decline ? { declined: true } : draft()
submitting.value = true
try {
const { resumed } = await (embedTarget()
? resolveEmbedAgentPrompt(
props.embedChannelId!, props.embedToken!, props.embedSessionId!, props.embedSessionSig!,
props.embedVisitorId!, props.pendingId, 'ask_user', response,
)
: resolveAgentPrompt(props.pendingId, 'ask_user', response))
markPromptSubmitted(props.pendingId, response)
if (resumed) resumeSuspendedRun?.(props.pendingId)
} catch (e: any) {
const msg = e?.response?.data?.error?.message || e?.error?.message || e?.message
|| t('agentStream.askUser.submitFailed')
MessagePlugin.error(msg)
} finally {
submitting.value = false
}
}
/** Keyboard shortcuts while docked: a letter picks an option, Enter submits. */
const handleKey = (e: KeyboardEvent): boolean => {
if (!interactive.value) return false
const target = e.target as HTMLElement | null
if (isSubmitKey(e)) {
// Enter inside a select picks from its dropdown.
if (target?.closest('.t-select, .t-select__wrap')) return false
void submit(false)
return true
}
if (isTextEntry(target) || e.metaKey || e.ctrlKey || e.altKey) return false
const index = optionIndexForKey(e.key)
if (index < 0 || index >= options.value.length) return false
toggleOption(options.value[index])
return true
}
defineExpose({ handleKey })
</script>
<style scoped lang="less">
@import './agent-interaction-card.less';
.ask-inline {
min-width: 0;
.action-title {
column-gap: 8px;
row-gap: 4px;
}
.action-name {
font-size: var(--agent-step-summary-size, 13px);
}
}
.ask-status {
padding: 1px 6px;
border-radius: var(--app-radius-sm, 4px);
background: var(--td-bg-color-secondarycontainer);
color: var(--td-text-color-secondary);
font-size: var(--app-text-xs, 12px);
line-height: 1.5;
}
.ask-question {
margin-top: 6px;
font-size: var(--agent-step-summary-size, 13px);
line-height: 1.65;
color: var(--td-text-color-secondary);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.ask-field {
display: flex;
flex-direction: column;
gap: 6px;
}
.ask-field-label {
font-size: var(--agent-step-summary-size, 13px);
line-height: 1.55;
color: var(--td-text-color-secondary);
}
.ask-number {
width: 100%;
}
.ask-field-options {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 150px), 1fr));
gap: 6px;
max-height: 200px;
overflow-y: auto;
overscroll-behavior: contain;
padding: 2px;
}
.ask-field-option {
position: relative;
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
padding: 9px 10px;
border: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-md);
background: var(--td-bg-color-container);
color: var(--td-text-color-primary);
font-size: var(--agent-step-summary-size, 13px);
line-height: 1.5;
cursor: pointer;
transition: background var(--app-motion-fast) ease, border-color var(--app-motion-fast) ease;
&:hover:not(.is-disabled) { background: var(--td-bg-color-container-hover); }
&.is-selected {
background: var(--td-bg-color-secondarycontainer);
border-color: var(--td-component-border);
}
&:has(input:focus-visible) { outline: 2px solid var(--td-brand-color); outline-offset: 1px; }
&.is-disabled { opacity: .5; cursor: not-allowed; }
input { position: absolute; width: 1px; height: 1px; opacity: 0; }
}
.ask-field-option-text { min-width: 0; overflow-wrap: anywhere; }
.ask-field-option-mark {
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 15px;
height: 15px;
border: 1px solid var(--td-component-border);
border-radius: var(--app-radius-xs, 3px);
color: transparent;
}
.is-selected .ask-field-option-mark {
background: var(--td-brand-color);
border-color: var(--td-brand-color);
color: var(--td-text-color-anti);
}
// Filled, borderless fields, like the option rows and argument editor of the
// other prompts in the dock.
.ask-field :deep(.t-input),
.ask-text :deep(.t-textarea__inner) {
min-height: 32px;
border-color: transparent;
border-radius: var(--app-radius-md);
background: var(--td-bg-color-secondarycontainer);
box-shadow: none;
font-size: var(--agent-step-summary-size, 13px);
transition: background var(--app-motion-fast) ease, border-color var(--app-motion-fast) ease;
&:hover:not(.t-is-disabled):not(.t-input--focused):not(:focus) {
border-color: transparent;
background: var(--td-bg-color-secondarycontainer-hover);
}
}
.ask-field :deep(.t-input.t-input--focused),
.ask-text :deep(.t-textarea__inner:focus) {
border-color: color-mix(in srgb, var(--td-brand-color) 45%, var(--td-component-stroke));
background: var(--td-bg-color-container);
box-shadow: none;
}
.ask-field :deep(.t-input__inner::placeholder),
.ask-text :deep(.t-textarea__inner::placeholder) {
color: var(--td-text-color-placeholder);
}
.ask-text {
// The limit is far above a typical answer; the counter is noise here.
:deep(.t-textarea__info_wrapper),
:deep(.t-textarea__limit) {
display: none;
}
}
.ask-answer {
display: flex;
flex-direction: column;
gap: 4px;
margin-top: 10px;
padding: 10px 12px;
border-radius: var(--app-radius-md, 8px);
background: var(--td-bg-color-secondarycontainer);
}
.ask-answer-label {
font-size: var(--app-text-xs, 12px);
line-height: 1.5;
color: var(--td-text-color-secondary);
}
.ask-answer-text {
font-size: var(--agent-step-text-size, 14px);
line-height: 1.6;
color: var(--td-text-color-primary);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.ask-required {
margin-left: 2px;
color: var(--td-error-color);
}
</style>
@@ -0,0 +1,51 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { runInNewContext } from 'node:vm'
import test from 'node:test'
import { compileScript, parse } from '@vue/compiler-sfc'
import * as vue from 'vue'
import ts from 'typescript'
const source = readFileSync(new URL('./BackgroundWorkChip.vue', import.meta.url), 'utf8')
const { descriptor } = parse(source)
const compiled = compileScript(descriptor, { id: 'background-work-chip' })
const exports: any = {}
runInNewContext(ts.transpileModule(compiled.content, {
compilerOptions: { module: ts.ModuleKind.CommonJS },
}).outputText, {
exports, Date, Set, setInterval, clearInterval,
require: () => ({ ...vue, onUnmounted() {} }),
})
for (const rejected of [false, true]) {
test(`cancel button re-enables when request settles (${rejected ? 'failure' : 'success'})`, async () => {
let finish!: () => void
let fail!: (reason: Error) => void
let calls = 0
const props = vue.reactive({
items: [{ work_id: 'sj_0123', kind: 'shell', state: 'running', title: 'build' }],
cancelWork: () => {
calls++
return new Promise<void>((resolve, reject) => { finish = resolve; fail = reject })
},
})
const scope = vue.effectScope()
const state = scope.run(() => exports.default.setup(props, { expose() {}, emit() {} }))
try {
const pending = state.onCancel('sj_0123')
assert.equal(state.cancelling.value.has('sj_0123'), true)
await state.onCancel('sj_0123')
assert.equal(calls, 1, 'duplicate clicks are suppressed while pending')
if (rejected) {
fail(new Error('HTTP 503'))
await assert.rejects(pending, /503/)
} else { finish(); await pending }
assert.equal(props.items[0].state, 'running', 'poll may still show a running job')
assert.equal(state.cancelling.value.has('sj_0123'), false)
const retry = state.onCancel('sj_0123')
assert.equal(calls, 2)
finish()
await retry
} finally { scope.stop() }
})
}
@@ -0,0 +1,218 @@
<template>
<t-popup
v-if="running.length"
v-model:visible="open"
trigger="click"
placement="top-left"
:overlay-inner-style="{ padding: '6px' }"
>
<button
type="button"
class="chip-count"
:aria-expanded="open"
:aria-label="$t('chat.backgroundWork.running', { count: running.length }, running.length)"
>
<span class="chip-badge" aria-hidden="true" />
<span>{{ $t('chat.backgroundWork.running', { count: running.length }, running.length) }}</span>
</button>
<template #content>
<div class="work-card" role="list">
<div v-for="item in running" :key="item.work_id" class="work-row" role="listitem">
<button type="button" class="work-main" @click="openOutput(item.work_id)">
<span class="work-title">{{ item.title || item.work_id }}</span>
<span v-if="elapsed(item)" class="work-duration">{{ elapsed(item) }}</span>
</button>
<button
type="button"
class="work-stop"
:disabled="cancelling.has(item.work_id)"
@click="onCancel(item.work_id)"
>{{ $t('chat.backgroundWork.stop') }}</button>
</div>
</div>
</template>
</t-popup>
</template>
<script setup lang="ts">
import { computed, onUnmounted, ref, watch } from 'vue'
import type { BackgroundWorkItem } from '@/api/chat/background-work'
const props = defineProps<{
items: BackgroundWorkItem[]
cancelWork: (workId: string) => Promise<void>
}>()
const emit = defineEmits<{ view: [workId: string] }>()
const cancelling = ref(new Set<string>())
const open = ref(false)
const now = ref(Date.now())
let clock: ReturnType<typeof setInterval> | undefined
const running = computed(() => props.items.filter((item) => item.state === 'running'))
function syncClock() {
const live = running.value.some((item) => item.started_at)
if (live && !clock) {
clock = setInterval(() => { now.value = Date.now() }, 1000)
} else if (!live && clock) {
clearInterval(clock)
clock = undefined
}
}
watch(running, (items) => {
syncClock()
if (!items.length) open.value = false
const ids = new Set(items.map((item) => item.work_id))
const next = new Set([...cancelling.value].filter((id) => ids.has(id)))
if (next.size !== cancelling.value.size) cancelling.value = next
}, { deep: true, immediate: true })
onUnmounted(() => {
if (clock) clearInterval(clock)
})
function openOutput(workId: string) {
open.value = false
emit('view', workId)
}
async function onCancel(workId: string) {
if (cancelling.value.has(workId)) return
const next = new Set(cancelling.value)
next.add(workId)
cancelling.value = next
try {
await props.cancelWork(workId)
} finally {
// The request may fail while the job remains running. Always permit retry
// after it settles; only an in-flight request should disable the button.
const remaining = new Set(cancelling.value)
remaining.delete(workId)
cancelling.value = remaining
}
}
function formatDuration(ms: number): string {
const seconds = Math.max(0, Math.floor(ms / 1000))
if (seconds < 60) return `${seconds}s`
const minutes = Math.floor(seconds / 60)
if (minutes < 60) return `${minutes}m ${seconds % 60}s`
const hours = Math.floor(minutes / 60)
return `${hours}h ${minutes % 60}m`
}
function elapsed(item: BackgroundWorkItem): string {
const start = Date.parse(item.started_at ?? '')
if (!Number.isFinite(start)) return ''
return formatDuration(now.value - start)
}
</script>
<style lang="less" scoped>
.chip-count {
display: inline-flex;
align-items: center;
gap: 6px;
flex-shrink: 0;
height: 28px;
margin: 0;
padding: 0 10px;
border: 0;
border-radius: var(--app-radius-sm);
background: transparent;
color: var(--td-text-color-secondary);
font: inherit;
font-size: var(--app-text-md);
font-weight: 500;
line-height: 18px;
cursor: pointer;
transition: background var(--app-motion-instant), color var(--app-motion-instant);
&:hover,
&[aria-expanded='true'] {
background: var(--td-bg-color-secondarycontainer-hover);
color: var(--td-text-color-primary);
}
}
.chip-badge {
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
}
.work-card {
display: flex;
flex-direction: column;
gap: 4px;
width: min(320px, 72vw);
max-height: 280px;
overflow: auto;
}
.work-row {
display: flex;
align-items: center;
gap: 8px;
}
.work-main {
display: flex;
align-items: baseline;
gap: 8px;
flex: 1;
min-width: 0;
margin: 0;
padding: 6px 8px;
border: 0;
border-radius: var(--td-radius-medium);
background: transparent;
color: var(--td-text-color-primary);
font: inherit;
font-size: var(--app-text-sm);
line-height: 18px;
text-align: left;
cursor: pointer;
&:hover {
background: var(--td-bg-color-secondarycontainer-hover);
}
}
.work-title {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.work-duration {
flex-shrink: 0;
color: var(--td-text-color-placeholder);
font-variant-numeric: tabular-nums;
}
.work-stop {
flex-shrink: 0;
margin: 0;
padding: 4px 8px;
border: 0;
border-radius: var(--td-radius-medium);
background: transparent;
color: var(--td-text-color-secondary);
font: inherit;
font-size: var(--app-text-sm);
line-height: 18px;
cursor: pointer;
&:hover {
background: var(--td-bg-color-secondarycontainer-hover);
}
&:disabled {
cursor: default;
opacity: 0.45;
}
}
</style>
@@ -0,0 +1,48 @@
<template>
<div class="background-work-results">
<div v-if="loading" class="results-loading">{{ $t('chat.backgroundWork.loading') }}</div>
<ShellExecResult v-else-if="detail?.result" :data="detail.result" />
<div v-else class="results-error">{{ $t('chat.backgroundWork.unavailable') }}</div>
</div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { getBackgroundWork, type BackgroundWorkDetail } from '@/api/chat/background-work'
import ShellExecResult from './tool-results/ShellExecResult.vue'
const props = defineProps<{ sessionId: string; workId: string }>()
const detail = ref<BackgroundWorkDetail | null>(null)
const loading = ref(false)
let request = 0
watch(() => [props.sessionId, props.workId] as const, async ([sessionId, id]) => {
if (!sessionId || !id) return
const current = ++request
loading.value = true
detail.value = null
try {
const next = await getBackgroundWork(sessionId, id)
if (current !== request) return
detail.value = next
} catch {
if (current !== request) return
detail.value = null
} finally {
if (current === request) loading.value = false
}
}, { immediate: true })
</script>
<style lang="less" scoped>
.background-work-results {
min-width: 0;
}
.results-loading,
.results-error {
font-size: var(--app-text-sm);
line-height: 1.4;
color: var(--td-text-color-placeholder);
}
</style>
@@ -0,0 +1,102 @@
// Run with BROWSERSKILL_TEST_CHROMIUM and BROWSERSKILL_TEST_PLAYWRIGHT.
import assert from 'node:assert/strict'
import test from 'node:test'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { createServer } from 'vite'
import vue from '@vitejs/plugin-vue'
const enabled = process.env.BROWSERSKILL_TEST_CHROMIUM && process.env.BROWSERSKILL_TEST_PLAYWRIGHT
test('human handoff expands, stays reachable on narrow screens, focuses the browser, and collapses after completion', { skip: !enabled }, async () => {
const root = fileURLToPath(new URL('../../../../', import.meta.url))
const server = await createServer({
root, cacheDir: root+'/node_modules/.vite-browser-preview-test', configFile: false, plugins: [vue(), {
name: 'preview-fixture',
enforce: 'pre',
transform(code, id) {
if (id.split('?')[0].endsWith('/BrowserTaskPreview.vue')) return code.replaceAll("'@/utils/request'", "'/fixture-api.js'")
},
configureServer(server) {
server.middlewares.use((req, res, next) => {
if (req.url === '/fixture') {
res.setHeader('Content-Type', 'text/html')
res.end('<div id="app"></div><script type="module" src="/fixture-entry.js"></script>')
} else next()
})
},
resolveId(id) { if (id === '/fixture-api.js' || id === '/fixture-entry.js') return '\0'+id },
load(id) {
if (id === '\0/fixture-api.js') return `
export async function get() { return {data:{...window.fixtureStatus}} }
export async function post(_, {action}) {
window.fixtureActions.push(action);
return {data: action === 'preview' ? {image_base64:window.fixtureFrame || '',format:'png'} : {...window.fixtureStatus}};
}`
if (id === '\0/fixture-entry.js') return `
import {createApp} from 'vue'; import {createPinia} from 'pinia';
import {createI18n} from 'vue-i18n'; import TDesign from 'tdesign-vue-next';
import {createRouter, createMemoryHistory} from 'vue-router';
import 'tdesign-vue-next/es/style/index.css';
import Preview from '/src/views/chat/components/BrowserTaskPreview.vue';
import zh from '/src/i18n/locales/zh-CN.ts';
window.fixtureActions=[];
window.fixtureStatus={enabled:true,selected:true,connected:true,task_id:'fixture',needs_help:false};
createApp(Preview,{sessionId:'fixture'}).use(createPinia()).use(createRouter({history:createMemoryHistory(),routes:[{path:'/:p(.*)*',component:{render:()=>null}}]})).use(TDesign).use(createI18n({legacy:false,locale:'zh-CN',messages:{'zh-CN':zh}})).mount('#app');`
},
}], resolve: {alias: {'@': root+'/src'}}, server: {host:'127.0.0.1',port:0},
})
const { chromium } = await import(pathToFileURL(process.env.BROWSERSKILL_TEST_PLAYWRIGHT).href)
let browser
try {
await server.listen()
browser = await chromium.launch({executablePath:process.env.BROWSERSKILL_TEST_CHROMIUM,headless:true})
const page = await browser.newPage({viewport:{width:1100,height:800}})
page.on('pageerror', error => console.error(error.message))
page.on('console', message => { if (message.type() === 'error') console.error(message.text()) })
await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/fixture`)
const card = page.locator('.browser-task-preview')
await card.waitFor()
assert.equal(Math.round((await card.boundingBox()).width),320)
// A new frame can change aspect ratio when the source browser is resized.
for (const [width, height] of [[1200, 600], [600, 900]]) {
await page.evaluate(([width, height]) => {
const canvas = document.createElement('canvas')
canvas.width = width; canvas.height = height
window.fixtureFrame = canvas.toDataURL('image/png').split(',')[1]
}, [width, height])
await page.waitForFunction(([width, height]) => {
const image = document.querySelector('.preview-image img')
return image?.naturalWidth === width && image?.naturalHeight === height
}, [width, height])
const image = await page.locator('.preview-image img').boundingBox()
const frame = await page.locator('.preview-image').boundingBox()
assert.ok(Math.abs(image.width / image.height - width / height) < 0.01, 'preserve source aspect ratio')
assert.ok(Math.abs(frame.height - image.height) <= 2, 'frame follows image without a fixed-height gap')
}
await page.evaluate(() => {
window.fixtureStatus.needs_help=true
window.fixtureStatus.help_prompt='请在浏览器中扫码登录,完成后确认。'.repeat(18)
})
await page.waitForSelector('.needs-help .preview-handoff')
assert.equal(Math.round((await card.boundingBox()).width),420)
const focus = page.locator('.preview-handoff button')
await focus.click()
assert.ok(await page.evaluate(() => window.fixtureActions.includes('focus')))
await page.setViewportSize({width:320,height:480})
await page.waitForTimeout(200)
const bounds = await card.boundingBox()
assert.ok(bounds.x >= 0 && bounds.x+bounds.width <= 320)
await focus.click()
const buttonBounds = await focus.boundingBox()
assert.ok(buttonBounds.y >= 0 && buttonBounds.y+buttonBounds.height <= 480)
if (process.env.BROWSERSKILL_TEST_PREVIEW_FILE) await page.screenshot({path:process.env.BROWSERSKILL_TEST_PREVIEW_FILE})
await page.evaluate(() => { window.fixtureStatus.action='tab_borrow'; window.fixtureStatus.help_prompt='' })
await page.waitForFunction(() => document.querySelector('.preview-handoff')?.textContent.includes('不代替借用授权'))
assert.equal(await page.locator('.preview-handoff button').count(),0)
assert.equal(await page.locator('.preview-image').count(),0,'do not focus the unrelated task blank tab during borrow confirmation')
await page.evaluate(() => { window.fixtureStatus.needs_help=false; window.fixtureStatus.help_prompt='' })
await page.waitForFunction(() => !document.querySelector('.needs-help'))
assert.equal(await page.locator('.preview-handoff').count(),0)
assert.equal(Math.round((await card.boundingBox()).width),280)
} finally { await browser?.close(); await server.close() }
})
@@ -0,0 +1,219 @@
<template>
<Teleport :to="pipTarget || 'body'" :disabled="!pipTarget">
<aside v-if="status.selected" ref="previewElement" class="browser-task-preview"
:class="{ 'is-dragging': dragging, 'is-pip': !!pipTarget, 'needs-help': status.needs_help }"
:style="pipTarget ? {} : positionStyle" :aria-label="t('localBrowser.preview')">
<div class="preview-heading" @pointerdown="!pipTarget && startDrag($event)" @pointermove="moveDrag"
@pointerup="stopDrag" @pointercancel="stopDrag" @lostpointercapture="stopDrag">
<BrowserIcon class="preview-browser-icon" width="16" height="16" />
<strong :title="pageAddress || t('localBrowser.controlScope')">{{ pageHost || t('localBrowser.local') }}</strong>
<button v-if="!(status.needs_help && status.action === 'tab_borrow')" class="preview-popout"
:disabled="!status.connected || !status.task_id || busy || status.stopping"
:title="t('localBrowser.locateWindow')" :aria-label="t('localBrowser.locateWindow')"
@pointerdown.stop @click="act('focus')"><t-icon name="jump" size="15px" /></button>
<button v-if="pipSupported" class="preview-popout" :disabled="pipOpening"
:title="t(pipTarget ? 'localBrowser.pipReturn' : 'localBrowser.pipOpen')"
:aria-label="t(pipTarget ? 'localBrowser.pipReturn' : 'localBrowser.pipOpen')"
@pointerdown.stop @click="togglePictureInPicture"><t-icon :name="pipTarget ? 'fullscreen-exit' : 'fullscreen'" size="15px" /></button>
</div>
<section v-if="status.needs_help" class="preview-handoff" role="status" aria-live="polite">
<strong>{{ t('localBrowser.needHelp') }}</strong>
<p v-if="status.help_prompt" class="handoff-prompt">{{ status.help_prompt }}</p>
<p>{{ t(status.action === 'tab_borrow' ? 'localBrowser.borrowHint' : 'localBrowser.helpHint') }}</p>
<t-button v-if="status.action !== 'tab_borrow'" class="handoff-locate" theme="default" variant="outline" size="small"
:disabled="!status.connected || !status.task_id || busy || status.stopping" @click="act('focus')">
<t-icon name="jump" />{{ t('localBrowser.locateWindow') }}
</t-button>
</section>
<button v-if="!(status.needs_help && status.action === 'tab_borrow')" class="preview-image" :class="{ 'is-empty': !preview }"
:disabled="!status.connected || !status.task_id || busy || status.stopping"
:aria-label="t('localBrowser.locateWindow')" :title="t('localBrowser.locateWindow')" @click="act('focus')">
<img v-if="preview" :src="preview" :alt="t('localBrowser.preview')" />
<span v-else class="preview-empty"><BrowserIcon width="28" height="28" />{{ t(status.connected ? 'localBrowser.waiting' : 'localBrowser.reconnectShort') }}</span>
</button>
<p v-if="status.last_error" class="preview-error" role="alert">{{ status.last_error }}</p>
<p v-if="pipFailed" class="preview-error" role="alert">{{ t('localBrowser.pipFailed') }}</p>
<p v-if="error" class="preview-error" role="alert">{{ error }}</p>
<div class="preview-toolbar" :aria-label="t('localBrowser.controlScope')">
<span class="preview-status" :class="{ live: status.connected && !status.paused && !status.stopping && !status.needs_help && !status.idle && !previewStale, attention: status.needs_help || status.paused }"
:title="statusDetail" role="status"><i /><span>{{ statusLabel }}</span></span>
<div class="preview-actions">
<button v-if="status.connected" class="preview-control"
:aria-label="t(status.paused ? 'localBrowser.resume' : 'localBrowser.pause')"
:title="t(status.paused ? 'localBrowser.resume' : 'localBrowser.pauseHint')"
:disabled="busy || status.stopping" @click="act(status.paused ? 'resume' : 'pause')">
<t-icon :name="status.paused ? 'play' : 'pause'" size="14px" />{{ t(status.paused ? 'localBrowser.resumeShort' : 'localBrowser.pauseShort') }}
</button>
<button v-else class="preview-control" @click="openBrowserSettings">{{ t('localBrowser.settingsTitle') }}</button>
<button class="preview-control" :title="t('localBrowser.stopHint')" :aria-label="t('localBrowser.stop')"
:disabled="busy || status.stopping" @click="act('stop')"><t-icon name="stop" size="14px" />{{ t('localBrowser.stopShort') }}</button>
</div>
</div>
</aside>
</Teleport>
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { get, post } from '@/utils/request'
import { useRouter } from 'vue-router'
import { toolboxLocation } from '@/config/toolbox'
import { browserActionLabel, browserPageAddress } from '@/utils/browserToolDisplay'
import BrowserIcon from '@/components/icons/BrowserIcon.vue'
import { useFloatingPreviewDrag } from '@/composables/useFloatingPreviewDrag'
import { useDocumentPictureInPicture } from '@/composables/useDocumentPictureInPicture'
const props = defineProps<{ sessionId: string }>()
const { t } = useI18n(), router = useRouter()
const status = ref({ enabled: false, selected: false, connected: false, paused: false, idle: false, needs_help: false, help_prompt: '', task_id: '', action: '', action_elapsed_ms: 0, page_url: '', last_error: '', stopping: false })
const busy = ref(false), error = ref(''), preview = ref(''), previewStale = ref(false)
const pageAddress = computed(() => browserPageAddress(status.value.page_url))
const pageHost = computed(() => pageAddress.value ? new URL(pageAddress.value).hostname : '')
const statusLabel = computed(() => {
const s = status.value
if (!s.connected) return t('localBrowser.offline')
if (s.stopping) return t('localBrowser.stopping')
if (s.needs_help) return t('localBrowser.needHelp')
if (s.paused) return t('localBrowser.paused')
if (s.idle) return t('localBrowser.previewIdle')
if (previewStale.value) return t('localBrowser.previewStale')
if (!s.task_id) return t('localBrowser.waiting')
if (s.action) return browserActionLabel(t, s.action)
return t(preview.value ? 'localBrowser.running' : 'localBrowser.previewLoading')
})
const statusDetail = computed(() => [
statusLabel.value,
status.value.action ? t('localBrowser.elapsedSeconds', { seconds: Math.floor((status.value.action_elapsed_ms || 0) / 1000) }) : '',
preview.value && !previewStale.value ? t('localBrowser.previewLive') : '',
].filter(Boolean).join(' · '))
const { supported: pipSupported, target: pipTarget, opening: pipOpening, open: openPiP, close: closePiP } = useDocumentPictureInPicture(computed(() => status.value.selected), () => t('localBrowser.preview'))
const previewElement = ref<HTMLElement | null>(null)
const { positionStyle, dragging, startDrag, moveDrag, stopDrag } = useFloatingPreviewDrag(computed(() => pipTarget.value ? null : previewElement.value))
const pipFailed = ref(false)
async function togglePictureInPicture() {
pipFailed.value = false
if (pipTarget.value) { closePiP(); window.focus(); return }
try { await openPiP() }
catch { if (alive) pipFailed.value = true }
}
function openBrowserSettings() {
closePiP()
window.focus()
void router.push(toolboxLocation('browserconnection'))
}
let lastFrame = 0
const endpoint = `/api/v1/sessions/${encodeURIComponent(props.sessionId)}/local-browser`
const controller = new AbortController()
let alive = true, cancelTimer: (() => void) | undefined, revision = 0
async function act(action: string) {
if (busy.value) return
busy.value = true; error.value = ''; revision++
try {
const result = await post<{ data: typeof status.value }>(endpoint, { action }, { timeout: 45000, signal: controller.signal })
if (alive) { status.value = result.data; if (action === 'stop') preview.value = '' }
} catch (e: any) { if (alive) error.value = e?.message || t('localBrowser.failed') }
finally { if (alive) busy.value = false }
}
let polling = false
async function poll() {
if (polling || !alive) return
polling = true
try {
if (!busy.value && (!document.hidden || pipTarget.value)) {
const current = revision
const result = await get<{ data: typeof status.value }>(endpoint, { signal: controller.signal })
if (!alive || current !== revision) return
status.value = result.data
if (!status.value.connected || !status.value.task_id) preview.value = ''
if (alive && !busy.value && status.value.selected && status.value.connected && status.value.task_id && (!status.value.idle || !preview.value)) {
const image = await post<{ data: { image_base64: string; format: string; captured_at: string } }>(endpoint, { action: 'preview' }, { timeout: 10000, signal: controller.signal })
if (alive && revision === current && image.data.image_base64 && ['png', 'jpeg'].includes(image.data.format)) { preview.value = `data:image/${image.data.format};base64,${image.data.image_base64}`; lastFrame = Date.parse(image.data.captured_at) || Date.now(); previewStale.value = false }
}
}
} catch { /* Background polling does not replace explicit action errors. */ }
finally {
polling = false
if (alive) {
previewStale.value = !!preview.value && Date.now() - lastFrame > 5000
// Schedule in the visible PiP document when the conversation is in the background.
const timerWindow = pipTarget.value?.ownerDocument.defaultView || window
const timer = timerWindow.setTimeout(poll, !status.value.enabled ? 30000 : status.value.selected && !status.value.idle ? 1000 : 5000)
cancelTimer = () => timerWindow.clearTimeout(timer)
}
}
}
const onVisible = () => { cancelTimer?.(); if (!document.hidden || pipTarget.value) void poll() }
watch(pipTarget, onVisible, { flush: 'post' })
onMounted(() => { document.addEventListener('visibilitychange', onVisible); void poll() })
onBeforeUnmount(() => { alive = false; document.removeEventListener('visibilitychange', onVisible); revision++; cancelTimer?.(); controller.abort(); preview.value = '' })
</script>
<style scoped>
.browser-task-preview {
position: absolute; right: 20px; bottom: 16px; width: 320px; max-width: calc(100% - 40px);
max-height: calc(100% - 24px); box-sizing: border-box; z-index: 5; overflow: auto;
background: var(--td-bg-color-container); border: 1px solid var(--td-component-stroke);
border-radius: 12px; box-shadow: 0 8px 28px #18252014, 0 2px 6px #18252008;
}
.preview-heading {
display: flex; align-items: center; gap: 8px; min-height: 38px; padding: 0 9px 0 12px;
cursor: grab; touch-action: none; user-select: none; position: sticky; top: 0; z-index: 1;
background: var(--td-bg-color-container);
}
.is-dragging .preview-heading { cursor: grabbing; }
.preview-browser-icon { flex-shrink: 0; color: var(--td-text-color-secondary); }
.preview-heading strong {
flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
font-size: var(--app-text-sm); font-weight: 500; color: var(--td-text-color-secondary);
}
.preview-image {
width: 100%; height: auto; border: 0; border-block: 1px solid var(--td-component-stroke);
background: var(--td-bg-color-secondarycontainer); color: var(--td-text-color-secondary);
display: grid; place-items: center; cursor: pointer; padding: 0; font-size: var(--app-text-xs);
}
.preview-image:disabled { cursor: default; }
.preview-image.is-empty { aspect-ratio: 16 / 9; }
.preview-image img { display: block; width: 100%; height: auto; min-height: 0; }
.preview-image:focus-visible { outline: 2px solid var(--td-brand-color); outline-offset: -2px; }
.preview-empty { display: flex; flex-direction: column; align-items: center; gap: 10px; padding: 12px; line-height: 1.5; }
.preview-empty svg { opacity: .45; }
.preview-toolbar { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; padding: 8px 10px 8px 12px; position: sticky; bottom: 0; background: var(--td-bg-color-container); }
.preview-status {
display: flex; align-items: center; gap: 6px; flex: 1 1 64px; min-width: 0; overflow: hidden;
white-space: nowrap; font-size: var(--app-text-xs); line-height: 1.5; color: var(--td-text-color-secondary);
}
.preview-status i { width: 5px; height: 5px; border-radius: 50%; background: currentColor; flex-shrink: 0; }
.preview-status > span { overflow: hidden; text-overflow: ellipsis; }
.preview-status.live i { background: var(--td-success-color); }
.preview-status.attention i { background: var(--td-warning-color); }
.preview-actions { display: flex; align-items: center; gap: 6px; flex-shrink: 0; margin-left: auto; }
.preview-control, .preview-popout {
display: inline-flex; align-items: center; justify-content: center; gap: 4px;
min-width: 28px; min-height: 28px; padding: 4px; border: 0; border-radius: 6px;
font: inherit; font-size: var(--app-text-xs); background: transparent;
color: var(--td-text-color-secondary); cursor: pointer; flex-shrink: 0;
transition: background-color .16s, color .16s;
}
.preview-control { box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--td-component-stroke); font-size: var(--app-text-sm); line-height: 18px; color: var(--td-text-color-primary); }
.preview-control :deep(.t-icon) { flex-shrink: 0; color: var(--td-text-color-secondary); }
.preview-control:not(:disabled):hover, .preview-popout:not(:disabled):hover { background: var(--td-bg-color-container-hover); color: var(--td-text-color-primary); }
.preview-control:focus-visible, .preview-popout:focus-visible { outline: 2px solid var(--td-brand-color); outline-offset: 1px; }
.preview-control:disabled, .preview-popout:disabled { opacity: .4; cursor: default; }
.preview-error { margin: 8px 12px; color: var(--td-error-color); font-size: var(--app-text-sm); line-height: 1.5; overflow-wrap: anywhere; }
.browser-task-preview.is-pip { position: static; width: 100%; max-width: none; height: 100dvh; max-height: none; border: 0; border-radius: 0; box-shadow: none; display: flex; flex-direction: column; }
.is-pip .preview-heading { cursor: default; flex-shrink: 0; }
.is-pip .preview-image { flex: 1; min-height: 0; overflow: hidden; aspect-ratio: auto; grid-template-rows: minmax(0, 1fr); }
.is-pip .preview-image img { height: 100%; object-fit: contain; }
.is-pip .preview-toolbar { margin-top: auto; flex-shrink: 0; }
.browser-task-preview.needs-help { width: 420px; }
.preview-handoff { display: flex; flex-direction: column; align-items: stretch; gap: 8px; padding: 16px; border-top: 1px solid var(--td-component-stroke); background: var(--td-bg-color-secondarycontainer); overflow-wrap: anywhere; }
.preview-handoff strong { font-size: var(--app-text-md); font-weight: 600; color: var(--td-text-color-primary); }
.preview-handoff p { font-size: var(--app-text-sm); line-height: 1.6; margin: 0; color: var(--td-text-color-secondary); white-space: pre-wrap; }
.preview-handoff .handoff-prompt { max-height: 22vh; overflow-y: auto; color: var(--td-text-color-primary); }
.preview-handoff .handoff-locate { align-self: flex-end; flex-shrink: 0; max-width: 100%; margin-top: 2px; }
.is-pip .preview-handoff { flex-shrink: 0; }
.browser-task-preview.is-pip.needs-help { width: 100%; }
@media(max-width:720px) { .browser-task-preview { right: 12px; bottom: 12px; width: 280px; max-width: calc(100% - 24px); } .preview-toolbar { padding-left: 8px; } }
@media(max-width:480px) { .browser-task-preview.needs-help { width: calc(100% - 24px); max-width: calc(100% - 24px); } .browser-task-preview.is-pip.needs-help { width: 100%; max-width: none; } }
@media(prefers-reduced-motion: reduce) { .preview-control, .preview-popout { transition: none; } }
</style>
@@ -0,0 +1,69 @@
import assert from 'node:assert/strict'
import { after, before, test } from 'node:test'
import { fileURLToPath } from 'node:url'
import { createServer, type ViteDevServer } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createSSRApp, h, type Component } from 'vue'
import { renderToString } from 'vue/server-renderer'
import { createI18n } from 'vue-i18n'
import zh from '../../../i18n/locales/zh-CN'
let server: ViteDevServer
let Card: Component
before(async () => {
server = await createServer({
configFile: false, optimizeDeps: { noDiscovery: true, entries: [] }, plugins: [vue()],
resolve: { alias: { '@': fileURLToPath(new URL('../../../', import.meta.url)) } },
server: { middlewareMode: true, hmr: false }, appType: 'custom',
})
Card = (await server.ssrLoadModule('/src/views/chat/components/BrowserToolDetails.vue')).default
})
after(async () => { await server?.close() })
async function render(event: Record<string, unknown>) {
const app = createSSRApp({ render: () => h(Card, { event }) })
app.use(createI18n({ legacy: false, locale: 'zh-CN', messages: { 'zh-CN': zh } }))
return renderToString(app)
}
test('observation card renders readable content and escapes page HTML', async () => {
const html = await render({success:true, output:JSON.stringify({text:'Search results <script>alert(1)</script>',tab_id:42,ref_count:3})})
assert.match(html, /Search results &lt;script&gt;/)
assert.doesNotMatch(html, /<script>|技术详情|tab_id|ref_count|\[object Object\]/)
})
test('screenshots render as images and tabs render as rows without raw JSON', async () => {
const image = await render({success:true,output:{image_base64:'aGVsbG8=',format:'png'}})
assert.match(image, /<img[^>]+src="data:image\/png;base64,aGVsbG8="/)
assert.doesNotMatch(image, /<pre|image_base64/)
const tabs = await render({success:true,output:JSON.stringify({tabs:[{tab_id:7,title:'News',url:'https://user:password@example.com/news?token=secret'}]})})
assert.match(tabs, /<strong[^>]*>News<\/strong>/)
assert.match(tabs, /https:\/\/example.com\/news/)
assert.doesNotMatch(tabs, /password|secret|tab_id|技术详情/)
})
test('interrupted and historical actions do not claim success', async () => {
const failed = await render({success:false,error:'browser command interrupted or timed out'})
assert.match(failed, /浏览器操作已中断/)
assert.doesNotMatch(failed, /操作已完成/)
const old = await render({output:'{}'})
assert.match(old, /已记录浏览器操作/)
assert.doesNotMatch(old, /操作已完成/)
})
test('flat argument validation failures identify invalid tool input', async () => {
const html = await render({success:false,error:"Parameter validation failed: navigate requires url at the top level"})
assert.match(html, /浏览器工具参数格式错误或不完整/)
assert.doesNotMatch(html, /请检查当前页面后重试/)
})
test('diagnostics, script values, and navigation errors are rendered safely', async () => {
const logs = await render({arguments:{method:'console'},success:true,output:{entries:[{level:'error',text:'API <script>alert(1)</script>'}]}})
assert.match(logs,/API &lt;script&gt;/)
assert.doesNotMatch(logs,/<script>/)
const value = await render({arguments:{method:'evaluate'},success:true,output:{ok:true,value:{count:123}}})
assert.match(value,/count/)
assert.match(value,/123/)
const navigation = await render({arguments:{method:'navigate'},success:true,output:{reached:'timeout',error_text:'Loading did not finish'}})
assert.match(navigation,/Loading did not finish/)
assert.match(navigation,/未达到目标加载阶段/)
assert.doesNotMatch(navigation,/操作已完成/)
const image = await render({arguments:{method:'screenshot'},success:true,output:'{"width":1}',tool_data:{image_base64:'aGVsbG8=',format:'png'}})
assert.match(image,/<img[^>]+src="data:image\/png;base64,aGVsbG8="/)
})
@@ -0,0 +1,42 @@
<template>
<section class="browser-tool-details">
<p class="browser-result-status" :class="{ failed: browserToolIncomplete(event) }">{{ browserToolSummary(t, event) }}</p>
<p v-if="content.error" class="browser-result-error">{{ content.error }}</p>
<p v-if="content.recoveryHint" class="browser-result-hint">{{ content.recoveryHint }}</p>
<p v-if="content.empty">{{ t('localBrowser.noEntries') }}</p>
<p v-if="content.title" class="browser-page-title">{{ content.title }}</p>
<p v-if="content.address" class="browser-page-address">{{ content.address }}</p>
<p v-if="content.prompt" class="browser-help-prompt">{{ content.prompt }}</p>
<img v-if="content.image" class="browser-result-image" :src="content.image" :alt="t('localBrowser.preview')" />
<ul v-if="content.tabs.length" class="browser-result-tabs">
<li v-for="(tab, index) in content.tabs" :key="index">
<strong>{{ tab.title || t('localBrowser.untitledTab') }}</strong>
<span v-if="tab.address">{{ tab.address }}</span>
</li>
</ul>
<pre v-if="content.text" class="browser-page-content">{{ content.text }}</pre>
<p v-if="content.truncated" class="browser-content-note">{{ t('localBrowser.contentTruncated') }}</p>
</section>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { browserToolContent, browserToolSummary, browserToolIncomplete, type BrowserToolEvent } from '@/utils/browserToolDisplay'
const props = defineProps<{ event: BrowserToolEvent }>()
const { t } = useI18n()
const content = computed(() => browserToolContent(props.event))
</script>
<style scoped>
.browser-tool-details { min-width: 0; max-width: 100%; box-sizing: border-box; margin: 8px 0; padding: 12px 14px; border: 1px solid var(--td-component-border); border-radius: var(--app-radius-md); background: var(--td-bg-color-container); font-size: var(--app-text-md); color: var(--td-text-color-secondary); overflow: hidden; }
.browser-tool-details p { margin: 0 0 8px; line-height: 1.6; overflow-wrap: anywhere; }
.browser-tool-details p:last-child { margin-bottom: 0; }
.browser-result-error, .browser-result-status.failed { color: var(--td-error-color); }
.browser-page-title { color: var(--td-text-color-primary); font-weight: 500; }
.browser-page-address, .browser-content-note { font-size: var(--app-text-sm); }
.browser-result-image { display: block; max-width: 100%; max-height: 360px; object-fit: contain; margin: 8px 0; border-radius: var(--app-radius-sm); }
.browser-result-tabs { margin: 8px 0; padding: 0; list-style: none; max-height: 300px; overflow: auto; }
.browser-result-tabs li { display: grid; gap: 4px; padding: 8px 0; overflow-wrap: anywhere; }
.browser-result-tabs strong { color: var(--td-text-color-primary); font-weight: 500; }
.browser-result-tabs span { font-size: var(--app-text-sm); }
.browser-page-content { margin: 8px 0 0; max-height: 300px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; font-size: var(--app-text-sm); line-height: 1.6; padding: 10px; border-radius: var(--app-radius-sm); background: var(--td-bg-color-secondarycontainer); }
</style>
@@ -0,0 +1,147 @@
import assert from 'node:assert/strict'
import { after, before, test } from 'node:test'
import { fileURLToPath } from 'node:url'
import { createServer, type ViteDevServer } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createSSRApp, h, type Component } from 'vue'
import { renderToString } from 'vue/server-renderer'
import { createI18n } from 'vue-i18n'
import en from '../../../i18n/locales/en-US'
import zh from '../../../i18n/locales/zh-CN'
const REAL_COMPONENTS = [
'ToolResultRenderer.vue',
'OperationsResult.vue',
'WeKnoraDocResult.vue',
'CatalogValue.vue',
'DocMarkdown.vue',
]
let server: ViteDevServer
let Renderer: Component
before(async () => {
server = await createServer({
configFile: false, optimizeDeps: { noDiscovery: true, entries: [] }, plugins: [
{
name: 'isolate-catalog-renderer',
enforce: 'pre',
load(id) {
if (id.endsWith('.vue') && !REAL_COMPONENTS.some((name) => id.endsWith(`/${name}`))) {
return '<template><div /></template>'
}
},
},
vue(),
],
resolve: { alias: { '@': fileURLToPath(new URL('../../../', import.meta.url)) } },
server: { middlewareMode: true }, appType: 'custom',
})
Renderer = (await server.ssrLoadModule('/src/views/chat/components/ToolResultRenderer.vue')).default
})
after(async () => { await server?.close() })
async function render(props: Record<string, unknown>, locale = 'en-US') {
const app = createSSRApp({ render: () => h(Renderer, props) })
app.use(createI18n({ legacy: false, locale, messages: { 'en-US': en, 'zh-CN': zh } }))
app.component('t-icon', { render: () => h('span') })
return renderToString(app)
}
test('find_operations renders rows instead of raw JSON', async () => {
const html = await render({
displayType: 'find_operations',
success: true,
output: JSON.stringify({
operations: [{
id: 'knowledge.get', risk: 'read', summary: 'Read a knowledge base',
description: 'Returns <script>alert(1)</script>',
params: [{ name: 'knowledge_base_id', type: 'string', required: true, description: 'Knowledge base' }],
}],
unavailable: [{ id: 'knowledge.delete', risk: 'destructive', summary: 'Delete', reason: 'read-only' }],
hint: 'Call find_operations again',
}),
})
assert.match(html, /knowledge\.get/)
assert.match(html, /title="knowledge\.get"[^>]*>Get knowledge details</)
assert.match(html, /Read a knowledge base/)
assert.match(html, /Read</)
assert.match(html, /knowledge_base_id/)
assert.match(html, /Required/)
assert.match(html, /knowledge\.delete/)
assert.match(html, /title="knowledge\.delete"[^>]*>Delete knowledge</)
assert.match(html, /Destructive/)
assert.match(html, /&lt;script&gt;/)
assert.doesNotMatch(html, /fallback-output|hint|Call find_operations|<script>/)
})
test('run_operation renders projected fields and keeps failures out of the raw dump', async () => {
const html = await render({
displayType: 'run_operation',
success: true,
output: JSON.stringify({
operation: 'knowledge.list',
result: { data: [{ title: '员工手册', parse_status: 'failed' }], truncated: true },
}),
})
assert.match(html, /knowledge\.list/)
assert.match(html, /title="knowledge\.list"[^>]*>List knowledge</)
assert.match(html, /员工手册/)
assert.match(html, /parse_status/)
assert.match(html, /failed/)
assert.match(html, /Result truncated/)
assert.doesNotMatch(html, /fallback-output/)
const error = await render({ displayType: 'run_operation', success: false, output: 'unknown operation "nope"' })
assert.match(error, /role="alert"/)
assert.match(error, /unknown operation/)
assert.doesNotMatch(error, /fallback-output/)
})
test('operation results show localized names and retain IDs as tooltips', async () => {
for (const [operation, label] of [['model.list', '获取模型列表'], ['agent.list', '获取智能体列表'], ['future.unknown', 'future.unknown']]) {
const html = await render({
displayType: 'run_operation', success: true,
output: JSON.stringify({ operation, result: { data: [] } }),
}, 'zh-CN')
assert.ok(html.includes(`title="${operation}"`), html)
assert.ok(html.includes(`>${label}</span>`), html)
}
})
test('product docs render pages, sections, and markdown instead of raw JSON', async () => {
const search = await render({
displayType: 'search_weknora_docs',
success: true,
output: JSON.stringify({
results: [{
path: '03-features/14-wiki', anchor: 'setup', section: '安装',
url: 'javascript:alert(1)', snippet: '<script>alert(1)</script>',
}],
}),
})
assert.match(search, /安装/)
assert.match(search, /03-features\/14-wiki#setup/)
assert.match(search, /&lt;script&gt;/)
assert.doesNotMatch(search, /javascript:|fallback-output|<script>/)
const read = await render({
displayType: 'read_weknora_doc',
success: true,
output: JSON.stringify({
title: 'Wiki',
path: '03-features/14-wiki',
section: '安装',
url: 'https://docs.example/wiki#setup',
content: '# 安装\n\n先准备 [环境](https://docs.example/env)。',
outline: [{ anchor: 'setup', heading: '安装', level: 2 }],
truncated: true,
}),
})
assert.match(read, /<h1 class="doc-h doc-h-1"/)
assert.match(read, /安装/)
assert.match(read, /href="https:\/\/docs\.example\/env"/)
assert.match(read, /href="https:\/\/docs\.example\/wiki#setup"/)
assert.match(read, /Open in docs/)
assert.match(read, /The page continues/)
assert.doesNotMatch(read, /fallback-output|"content"/)
})
@@ -0,0 +1,682 @@
<template>
<!--
ChatArtifactsDrawer — right-side drawer that lists every skill-generated
file attached to the surrounding assistant message, and opens an inline
preview that reuses DocumentPreview (same renderer as knowledge files
and chat attachments).
Usage (from botmsg.vue / AgentStreamDisplay.vue):
<ChatArtifactsDrawer
v-model:visible="showArtifacts"
:session-id="sessionId"
:message-id="messageId"
:artifacts="artifacts"
/>
-->
<teleport to="body">
<div
v-if="previewResizing"
class="artifact-preview-resize-overlay"
aria-hidden="true"
/>
<div
v-if="internalVisible && previewItem"
class="artifact-preview-resize-handle"
:class="{ 'artifact-preview-resize-handle--active': previewResizing }"
:style="{ right: drawerSize }"
role="separator"
aria-orientation="vertical"
@mousedown.prevent="onPreviewResizeStart"
>
<div class="artifact-preview-resize-line" />
</div>
</teleport>
<t-drawer
v-model:visible="internalVisible"
class="chat-artifacts-drawer"
:class="{ 'chat-artifacts-drawer--preview': !!previewItem, 'chat-artifacts-drawer--resizing': previewResizing }"
placement="right"
:size="drawerSize"
:z-index="2000"
attach="body"
:footer="false"
:close-btn="true"
:close-on-overlay-click="true"
:close-on-esc-keydown="true"
:destroy-on-close="false"
@close="handleClose"
>
<template #header>
<div v-if="previewItem" class="artifact-drawer-header artifact-drawer-header--preview">
<t-button
class="artifact-back"
variant="text"
shape="square"
size="small"
:title="$t('agent.artifactDrawer.previewBack')"
:aria-label="$t('agent.artifactDrawer.previewBack')"
@click="closePreview"
>
<template #icon>
<t-icon name="chevron-left" size="18px" />
</template>
</t-button>
<div class="artifact-drawer-header-icon">
<t-icon :name="getFileIcon(previewItem.file_name)" />
</div>
<div class="artifact-drawer-header-title" :title="previewItem.file_name">{{ previewItem.file_name }}</div>
<t-button
class="artifact-download"
variant="text"
shape="square"
size="small"
:title="$t('agent.artifactDrawer.download')"
:loading="!!downloading[previewItem.index]"
@click="handleDownload(previewItem)"
>
<template #icon>
<t-icon name="download" size="16px" />
</template>
</t-button>
<div ref="previewActions" class="artifact-preview-actions" />
</div>
<div v-else class="artifact-drawer-header">
<div class="artifact-drawer-header-icon">
<t-icon name="folder" />
</div>
<div class="artifact-drawer-header-title">{{ $t('agent.artifactDrawer.title') }}</div>
</div>
</template>
<div v-if="previewItem" class="artifact-preview-body">
<DocumentPreview
:toolbar-target="previewActions"
:session-id="sessionId"
:message-id="messageId"
:artifact-index="previewItem.index"
:file-type="previewFileType"
:file-name="previewItem.file_name"
:active="internalVisible"
fill-height
/>
</div>
<div v-else-if="loading" class="artifact-drawer-empty">
<t-loading size="small" />
<span>{{ $t('common.loading') }}</span>
</div>
<div v-else-if="!items.length" class="artifact-drawer-empty">
<t-icon name="folder-open" size="32px" />
<span>{{ $t('agent.artifactDrawer.empty') }}</span>
</div>
<ul v-else class="artifact-list">
<li
v-for="item in items"
:key="`${item.index}-${item.file_name}`"
class="artifact-item is-previewable"
@click="openPreview(item)"
>
<span class="artifact-icon">
<t-icon :name="getFileIcon(item.file_name)" />
</span>
<div class="artifact-body">
<div class="artifact-name" :title="item.file_name">{{ item.file_name }}</div>
<div class="artifact-meta">
<span>{{ formatFileSize(item.file_size) }}</span>
<span class="artifact-meta-sep">·</span>
<span>{{ formatDateTime(item.created_at) }}</span>
</div>
</div>
<t-button
class="artifact-preview-btn"
variant="text"
shape="square"
size="small"
:title="$t('agent.artifactDrawer.preview')"
@click.stop="openPreview(item)"
>
<template #icon>
<t-icon name="browse" size="16px" />
</template>
</t-button>
<t-button
class="artifact-download"
variant="text"
shape="square"
size="small"
:title="$t('agent.artifactDrawer.download')"
:loading="!!downloading[item.index]"
@click.stop="handleDownload(item)"
>
<template #icon>
<t-icon name="download" size="16px" />
</template>
</t-button>
</li>
</ul>
</t-drawer>
</template>
<script setup lang="ts">
/*
* Design notes:
* - The drawer is stateless w.r.t. the download itself; it delegates to
* the chat API's downloadArtifact() helper which uses the axios blob
* transport (getDown) so the Bearer token stays attached — plain
* <a href> would drop it and hit 401.
* - Preview reuses DocumentPreview so HTML charts, CSV tables, PDFs,
* images, office docs, audio/video, mermaid, and unlabeled text all
* go through the same renderer as knowledge-file / attachment preview.
* - `items` prefers the props-provided list (already in memory from the
* stream payload). When empty, we pull from /artifacts on open so a
* refreshed page still shows something without waiting for the parent
* to re-hydrate.
* - Errors during download are surfaced via MessagePlugin.error but do
* NOT close the drawer, matching spec §7: "抽屉保持打开以便重试其他文件".
* - Overlay / Esc while a file is previewed pop back to the list (same as
* the header chevron). TDesign still emits update:visible=false after
* @close, so we swallow that one emit; the header X still closes all.
*/
import { computed, onMounted, onUnmounted, ref, watch, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { MessagePlugin } from 'tdesign-vue-next'
import { downloadArtifact, listMessageArtifacts, type ArtifactMeta } from '@/api/chat'
import { getFileIcon } from '@/utils/files'
import { resolveFilePreviewExt } from '@/utils/filePreview'
import DocumentPreview from '@/components/document-preview.vue'
const LIST_WIDTH = 440
const PREVIEW_WIDTH_KEY = 'weknora-chat-artifact-preview-width'
const PREVIEW_DEFAULT_WIDTH = 760
const PREVIEW_MIN_WIDTH = 520
const props = defineProps<{
visible: boolean
sessionId: string
messageId: string
artifacts?: ArtifactMeta[]
/**
* Open straight into this artifact's preview instead of the list. Set when
* the drawer is opened by clicking an inline artifact card in the answer,
* where the user already picked the file.
*/
previewIndex?: number | null
}>()
const emit = defineEmits<{
(e: 'update:visible', v: boolean): void
}>()
const { t } = useI18n()
const previewActions = ref<HTMLElement | null>(null)
/** TDesign always follows @close with update:visible=false; swallow that when popping preview. */
let suppressDrawerClose = false
const internalVisible = computed({
get: () => props.visible,
set: (v: boolean) => {
if (!v && suppressDrawerClose) {
suppressDrawerClose = false
return
}
emit('update:visible', v)
},
})
const loading = ref(false)
const fetched = ref<ArtifactMeta[]>([])
const downloading = reactive<Record<number, boolean>>({})
const previewItem = ref<ArtifactMeta | null>(null)
// Opening the drawer from an inline artifact card jumps straight to the
// preview, so there is no list behind it to pop back to — overlay/Esc should
// dismiss the whole drawer. Coming from the list, they pop back to it.
const previewOpenedDirectly = ref(false)
const previewWidth = ref(PREVIEW_DEFAULT_WIDTH)
const previewResizing = ref(false)
let previewResizeStartX = 0
let previewResizeStartWidth = 0
const items = computed<ArtifactMeta[]>(() => {
if (props.artifacts && props.artifacts.length) return props.artifacts
return fetched.value
})
const previewFileType = computed(() => {
const item = previewItem.value
if (!item) return ''
return resolveFilePreviewExt(item.file_name, item.file_type)
})
const drawerSize = computed(() => (
`min(${previewItem.value ? previewWidth.value : LIST_WIDTH}px, 100%)`
))
function previewMaxWidth() {
return Math.min(1600, Math.max(PREVIEW_MIN_WIDTH, Math.floor(window.innerWidth * 0.95)))
}
function clampPreviewWidth(width: number) {
return Math.max(PREVIEW_MIN_WIDTH, Math.min(previewMaxWidth(), width))
}
function loadPreviewWidth() {
try {
const raw = localStorage.getItem(PREVIEW_WIDTH_KEY)
const parsed = raw ? parseInt(raw, 10) : NaN
if (!Number.isNaN(parsed)) {
previewWidth.value = clampPreviewWidth(parsed)
}
} catch {
/* ignore */
}
}
function onPreviewResizeStart(e: MouseEvent) {
previewResizing.value = true
previewResizeStartX = e.clientX
previewResizeStartWidth = previewWidth.value
document.addEventListener('mousemove', onPreviewResizeMove)
document.addEventListener('mouseup', onPreviewResizeEnd)
document.body.style.cursor = 'col-resize'
document.body.style.userSelect = 'none'
}
function onPreviewResizeMove(e: MouseEvent) {
const delta = previewResizeStartX - e.clientX
previewWidth.value = clampPreviewWidth(previewResizeStartWidth + delta)
}
function onPreviewResizeEnd() {
document.removeEventListener('mousemove', onPreviewResizeMove)
document.removeEventListener('mouseup', onPreviewResizeEnd)
document.body.style.cursor = ''
document.body.style.userSelect = ''
previewResizing.value = false
try {
localStorage.setItem(PREVIEW_WIDTH_KEY, String(previewWidth.value))
} catch {
/* ignore */
}
}
function cleanupPreviewResize() {
document.removeEventListener('mousemove', onPreviewResizeMove)
document.removeEventListener('mouseup', onPreviewResizeEnd)
document.body.style.cursor = ''
document.body.style.userSelect = ''
previewResizing.value = false
}
function onWindowResize() {
previewWidth.value = clampPreviewWidth(previewWidth.value)
}
watch(
() => props.visible,
async (open) => {
if (!open) {
suppressDrawerClose = false
previewItem.value = null
previewOpenedDirectly.value = false
return
}
if (props.artifacts && props.artifacts.length) {
fetched.value = []
applyRequestedPreview()
return
}
if (!props.sessionId || !props.messageId) return
loading.value = true
try {
const res: any = await listMessageArtifacts(props.sessionId, props.messageId)
const data = (res && (res.data || res)) as ArtifactMeta[] | undefined
fetched.value = Array.isArray(data) ? data : []
applyRequestedPreview()
} catch (err) {
console.error('[ChatArtifactsDrawer] load failed:', err)
fetched.value = []
} finally {
loading.value = false
}
},
)
// Clicking a second inline card while the drawer is already open should swap
// the preview rather than leave the previous file on screen.
watch(() => props.previewIndex, () => {
if (props.visible) applyRequestedPreview()
})
function applyRequestedPreview() {
if (!Number.isInteger(props.previewIndex as number)) return
const target = items.value.find((item) => item.index === props.previewIndex)
if (!target) return
previewItem.value = target
previewOpenedDirectly.value = true
}
function handleClose(context?: { trigger?: string }) {
const dismissedFromOutside = context?.trigger === 'overlay' || context?.trigger === 'esc'
const popPreview = !!previewItem.value && !previewOpenedDirectly.value && dismissedFromOutside
if (popPreview) {
closePreview()
suppressDrawerClose = true
return
}
previewItem.value = null
previewOpenedDirectly.value = false
emit('update:visible', false)
}
function openPreview(item: ArtifactMeta) {
previewItem.value = item
previewOpenedDirectly.value = false
}
function closePreview() {
previewItem.value = null
previewOpenedDirectly.value = false
}
function formatFileSize(size: number): string {
if (!size || size < 0) return '0 B'
const units = ['B', 'KB', 'MB', 'GB']
let s = size
let unit = 0
while (s >= 1024 && unit < units.length - 1) {
s /= 1024
unit++
}
return unit === 0 ? `${s} ${units[unit]}` : `${s.toFixed(1)} ${units[unit]}`
}
function formatDateTime(raw: string): string {
if (!raw) return '—'
const d = new Date(raw)
if (Number.isNaN(d.getTime())) return raw
const pad = (n: number) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
}
async function handleDownload(item: ArtifactMeta) {
if (!props.sessionId || !props.messageId) {
MessagePlugin.error(t('agent.artifactDrawer.downloadFailed'))
return
}
downloading[item.index] = true
try {
const blob = await downloadArtifact(props.sessionId, props.messageId, item.index)
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = item.file_name || 'artifact'
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
setTimeout(() => URL.revokeObjectURL(url), 1000)
} catch (err) {
console.error('[ChatArtifactsDrawer] download failed:', err)
MessagePlugin.error(t('agent.artifactDrawer.downloadFailed'))
} finally {
downloading[item.index] = false
}
}
onMounted(() => {
loadPreviewWidth()
window.addEventListener('resize', onWindowResize)
})
onUnmounted(() => {
window.removeEventListener('resize', onWindowResize)
cleanupPreviewResize()
})
</script>
<style lang="less" scoped>
.artifact-drawer-header {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
width: 100%;
padding-right: 32px;
}
.artifact-drawer-header--preview {
padding-right: 32px;
}
.artifact-back {
flex-shrink: 0;
color: var(--td-text-color-secondary);
:deep(.t-button__icon) {
margin: 0;
}
}
.artifact-preview-actions {
flex-shrink: 0;
}
.artifact-drawer-header-icon {
flex-shrink: 0;
width: 24px;
height: 24px;
border-radius: var(--app-radius-sm);
display: flex;
align-items: center;
justify-content: center;
background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
color: var(--td-brand-color);
font-size: var(--app-text-lg);
}
.artifact-drawer-header-title {
min-width: 0;
flex: 1;
font-size: var(--app-text-base);
font-weight: 500;
line-height: 20px;
color: var(--td-text-color-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.artifact-preview-body {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
height: 100%;
}
.artifact-drawer-empty {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
padding: 48px 16px;
color: var(--td-text-color-placeholder);
font-size: var(--app-text-md);
}
.artifact-list {
margin: 0;
padding: 0;
list-style: none;
}
.artifact-item {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 4px;
border-bottom: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-md);
&:last-child {
border-bottom: none;
}
&.is-previewable {
cursor: pointer;
}
&:hover {
background: var(--td-bg-color-container-hover);
}
&:hover .artifact-icon {
color: var(--td-brand-color);
}
}
.artifact-icon {
flex-shrink: 0;
width: 28px;
height: 28px;
border-radius: var(--app-radius-sm);
display: inline-flex;
align-items: center;
justify-content: center;
font-size: var(--app-text-xl);
background: var(--td-bg-color-secondarycontainer);
color: var(--td-text-color-secondary);
transition: color var(--app-motion-fast) ease;
}
.artifact-body {
flex: 1;
min-width: 0;
}
.artifact-name {
font-size: var(--app-text-base);
font-weight: 600;
letter-spacing: 0.01em;
line-height: 1.35;
color: var(--td-text-color-primary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.artifact-meta {
margin-top: 2px;
font-size: var(--app-text-sm);
line-height: 1.3;
color: var(--td-text-color-placeholder);
display: flex;
align-items: center;
gap: 4px;
}
.artifact-meta-sep {
opacity: 0.6;
}
.artifact-preview-btn,
.artifact-download {
flex-shrink: 0;
color: var(--td-text-color-secondary);
:deep(.t-button__icon) {
margin: 0;
}
}
.artifact-preview-resize-overlay {
position: fixed;
inset: 0;
z-index: 2001;
cursor: col-resize;
}
.artifact-preview-resize-handle {
position: fixed;
top: 0;
bottom: 0;
width: 12px;
margin-left: -6px;
// This drawer belongs to the conversation and overlays the assistant too.
z-index: 2002;
cursor: col-resize;
display: flex;
align-items: center;
justify-content: center;
}
.artifact-preview-resize-line {
width: 2px;
height: 48px;
border-radius: 1px;
background: var(--td-component-border);
opacity: 0.55;
transition: opacity var(--app-motion-fast) ease, background var(--app-motion-fast) ease;
}
.artifact-preview-resize-handle:hover .artifact-preview-resize-line,
.artifact-preview-resize-handle--active .artifact-preview-resize-line {
opacity: 1;
background: var(--td-brand-color);
}
</style>
<style lang="less">
.chat-artifacts-drawer.t-drawer {
.t-drawer__header {
height: var(--app-chat-header-height);
min-height: var(--app-chat-header-height);
padding: 0 12px;
border-bottom: 1px solid var(--td-component-stroke);
flex-shrink: 0;
font-weight: normal;
}
.t-drawer__close-btn {
top: calc((var(--app-chat-header-height) - 28px) / 2);
width: 28px;
height: 28px;
}
.t-drawer__body {
padding: 4px 20px 16px;
}
}
.t-drawer.chat-artifacts-drawer--preview {
.t-drawer__content-wrapper,
.t-drawer__content {
height: 100%;
}
.t-drawer__body {
flex: 1;
min-height: 0;
padding: 12px 16px 16px;
display: flex;
flex-direction: column;
overflow: hidden;
}
}
.t-drawer.chat-artifacts-drawer--resizing .t-drawer__content {
transition: none !important;
}
.t-drawer.chat-artifacts-drawer--resizing {
.artifact-preview-body,
.document-preview,
iframe,
.pdf-iframe,
.html-iframe {
pointer-events: none;
user-select: none;
}
}
</style>
@@ -0,0 +1,164 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import vm from 'node:vm'
import ts from 'typescript'
import { computed, effectScope, nextTick, reactive, ref, watch } from 'vue'
const source = readFileSync(new URL('./ChatArtifactsPanel.vue', import.meta.url), 'utf8')
const start = source.indexOf('function applyFocus(')
const end = source.indexOf('\nwatch(', start)
assert.ok(start >= 0 && end > start)
const applyFocusSource = ts.transpile(source.slice(start, end))
function setup({ top = 120, bottom = 180, left = 1600 } = {}) {
const pending = []
const scrolls = []
const target = { messageId: 'target', index: 0 }
const row = {
getAttribute: () => 'target',
getBoundingClientRect: () => ({ top, bottom, left, right: left + 400 }),
scrollIntoView: () => assert.fail('Artifact focus must not scroll outer ancestors'),
}
const list = {
scrollTop: 200,
getBoundingClientRect: () => ({ top: 100, bottom: 400, left, right: left + 420 }),
querySelectorAll: () => [row],
scrollTo: ({ top }) => scrolls.push(top),
}
const previewItem = { value: null }
const focusedMessageId = { value: null }
const applyFocus = vm.runInNewContext(`${applyFocusSource}; applyFocus`, {
listRef: { value: list }, previewItem, focusedMessageId,
nextTick: (fn) => pending.push(fn),
findItem: () => target,
})
return {
applyFocus, scrolls, previewItem, focusedMessageId, target,
flush: () => pending.splice(0).forEach((fn) => fn()),
}
}
test('folder focus during panel entry locates a visible file without scrolling ancestors', () => {
const ctx = setup()
ctx.applyFocus({ messageId: 'target', nonce: 1 })
ctx.flush()
assert.equal(ctx.focusedMessageId.value, 'target')
assert.deepEqual(ctx.scrolls, [])
})
test('folder focus reveals files above or below the list using only list scrolling', () => {
for (const [top, bottom, expected] of [[40, 100, 140], [380, 440, 240]]) {
const ctx = setup({ top, bottom })
ctx.applyFocus({ messageId: 'target', nonce: 1 })
ctx.flush()
assert.deepEqual(ctx.scrolls, [expected])
}
})
test('folder entry exits a preview and repeated clicks locate the file again', () => {
const ctx = setup({ top: 380, bottom: 440 })
ctx.applyFocus({ messageId: 'target', previewIndex: 0, nonce: 1 })
assert.equal(ctx.previewItem.value, ctx.target)
ctx.flush()
assert.deepEqual(ctx.scrolls, [])
for (const nonce of [2, 3]) {
ctx.applyFocus({ messageId: 'target', nonce })
ctx.flush()
assert.equal(ctx.previewItem.value, null)
}
assert.deepEqual(ctx.scrolls, [240, 240])
})
test('header entry without a message focus does not scroll the artifact list', () => {
const ctx = setup()
ctx.applyFocus(null)
ctx.flush()
assert.deepEqual(ctx.scrolls, [])
assert.equal(ctx.focusedMessageId.value, null)
})
const stateStart = source.indexOf('const listRef = ')
const stateEnd = source.indexOf('async function handleDownload(', stateStart)
assert.ok(stateStart >= 0 && stateEnd > stateStart)
const stateSource = ts.transpile(source.slice(stateStart, stateEnd))
function setupFilters(t) {
const effects = effectScope()
t.after(() => effects.stop())
const props = reactive({
sessionId: 'session-a',
items: [
{ messageId: 'a', index: 0, file_name: 'Report.docx' },
{ messageId: 'b', index: 3, file_name: 'Report.docx' },
{ messageId: 'b', index: 7, file_name: 'chart.png' },
],
})
const panel = {
artifactFocus: ref(null),
clearArtifactFocus() { this.artifactFocus.value = null },
}
const state = effects.run(() => vm.runInNewContext(`${stateSource}; ({
scope, searchQuery, currentItems, visibleItems, previewItem, openPreview, closePreview,
})`, {
computed, nextTick, reactive, ref, watch, props, panel,
resolveFilePreviewExt: () => '',
}))
return { ...state, props, panel }
}
test('header entry shows all files; folder entry filters by message without changing artifact indexes', async (t) => {
const ctx = setupFilters(t)
assert.equal(ctx.scope.value, 'all')
assert.equal(ctx.visibleItems.value.length, 3)
ctx.panel.artifactFocus.value = { messageId: 'b', nonce: 1 }
await nextTick()
assert.equal(ctx.scope.value, 'current')
assert.deepEqual(ctx.visibleItems.value.map((item) => item.index), [3, 7])
ctx.scope.value = 'all'
assert.equal(ctx.visibleItems.value.length, 3)
})
test('filename search combines with scope and survives incoming files', async (t) => {
const ctx = setupFilters(t)
ctx.panel.artifactFocus.value = { messageId: 'b', nonce: 1 }
await nextTick()
ctx.searchQuery.value = ' REPORT.DOCX '
assert.equal(ctx.visibleItems.value.length, 1)
ctx.scope.value = 'all'
assert.equal(ctx.visibleItems.value.length, 2)
ctx.props.items = [...ctx.props.items, { messageId: 'c', index: 0, file_name: 'Report.docx' }]
await nextTick()
assert.equal(ctx.scope.value, 'all')
assert.equal(ctx.searchQuery.value, ' REPORT.DOCX ')
assert.equal(ctx.visibleItems.value.length, 3)
ctx.searchQuery.value = 'missing'
assert.equal(ctx.visibleItems.value.length, 0)
})
test('switching message focus or session resets stale filters', async (t) => {
const ctx = setupFilters(t)
ctx.searchQuery.value = 'chart'
ctx.panel.artifactFocus.value = { messageId: 'a', nonce: 1 }
await nextTick()
assert.equal(ctx.searchQuery.value, '')
assert.equal(ctx.visibleItems.value[0].messageId, 'a')
ctx.props.sessionId = 'session-b'
await nextTick()
assert.equal(ctx.scope.value, 'all')
assert.equal(ctx.panel.artifactFocus.value, null)
})
test('preview returns to the selected scope and search', async (t) => {
const ctx = setupFilters(t)
ctx.panel.artifactFocus.value = { messageId: 'b', nonce: 1 }
await nextTick()
ctx.searchQuery.value = 'png'
ctx.openPreview(ctx.visibleItems.value[0])
assert.equal(ctx.previewItem.value.messageId, 'b')
assert.equal(ctx.previewItem.value.index, 7)
ctx.closePreview()
assert.equal(ctx.scope.value, 'current')
assert.equal(ctx.searchQuery.value, 'png')
assert.equal(ctx.visibleItems.value.length, 1)
})
@@ -0,0 +1,601 @@
<template>
<div class="chat-artifacts-panel">
<div v-if="previewItem" class="artifact-panel-header">
<t-button
class="artifact-back"
variant="text"
shape="square"
size="small"
:title="$t('agent.artifactDrawer.previewBack')"
:aria-label="$t('agent.artifactDrawer.previewBack')"
@click="closePreview"
>
<template #icon>
<t-icon name="chevron-left" size="18px" />
</template>
</t-button>
<ArtifactFileIcon class="artifact-panel-header-icon" :file-name="previewItem.file_name" />
<div class="artifact-panel-header-title" :title="previewItem.file_name">{{ previewItem.file_name }}</div>
<t-button
class="artifact-download"
variant="text"
shape="square"
size="small"
:title="$t('agent.artifactDrawer.download')"
:aria-label="$t('agent.artifactDrawer.download')"
:loading="isDownloading(previewItem)"
@click="handleDownload(previewItem)"
>
<template #icon>
<t-icon name="download" size="16px" />
</template>
</t-button>
<t-button
class="artifact-download artifact-delete"
variant="text"
shape="square"
size="small"
:title="$t('agent.artifactDrawer.delete')"
:aria-label="$t('agent.artifactDrawer.delete')"
:loading="isDeleting(previewItem)"
@click="handleDelete(previewItem)"
>
<template #icon>
<t-icon name="delete" size="16px" />
</template>
</t-button>
<div ref="previewActions" class="artifact-preview-actions" />
</div>
<div v-if="previewItem" class="artifact-preview-body">
<DocumentPreview
:toolbar-target="previewActions"
:session-id="sessionId"
:message-id="previewItem.messageId"
:artifact-index="previewItem.index"
:file-type="previewFileType"
:file-name="previewItem.file_name"
:active="active"
fill-height
/>
</div>
<div v-else-if="collecting && !items.length" class="artifact-panel-empty">
<t-loading size="small" />
<span>{{ $t('agent.artifactDrawer.collecting') }}</span>
</div>
<div v-else-if="!items.length" class="artifact-panel-empty">
<t-icon name="folder-open" size="32px" />
<span>{{ $t('chat.sandbox.artifactsEmpty') }}</span>
</div>
<template v-else>
<div class="artifact-filters">
<div class="artifact-scope" role="group" :aria-label="$t('chat.sandbox.artifactScope')">
<button
v-if="focusedMessageId"
type="button"
:aria-pressed="scope === 'current'"
@click="scope = 'current'"
>
{{ $t('chat.sandbox.artifactsCurrent') }}
<span>{{ currentItems.length }}</span>
</button>
<button type="button" :aria-pressed="scope === 'all'" @click="scope = 'all'">
{{ $t('chat.sandbox.artifactsAll') }}
<span>{{ items.length }}</span>
</button>
</div>
<t-input
v-model="searchQuery"
class="artifact-search"
:placeholder="$t('chat.sandbox.artifactsSearch')"
:aria-label="$t('chat.sandbox.artifactsSearch')"
clearable
>
<template #prefix-icon><t-icon name="search" size="16px" /></template>
</t-input>
</div>
<div v-if="collecting" class="artifact-panel-banner">
<t-icon name="loading" class="artifact-panel-banner-spin" />
<span>{{ $t('agent.artifactDrawer.collecting') }}</span>
</div>
<div v-if="!visibleItems.length" class="artifact-panel-empty">
<t-icon name="search" size="24px" />
<span>{{ $t('chat.sandbox.artifactsNoMatches') }}</span>
</div>
<ul v-show="visibleItems.length" ref="listRef" class="artifact-list">
<li
v-for="item in visibleItems"
:key="`${item.messageId}:${item.index}-${item.file_name}`"
class="artifact-item is-previewable"
:data-message-id="item.messageId"
:data-artifact-index="item.index"
@click="openPreview(item)"
>
<button type="button" class="artifact-open" :title="$t('agent.artifactDrawer.preview')">
<ArtifactFileIcon :file-name="item.file_name" />
<span class="artifact-body">
<span class="artifact-name" :title="item.file_name">{{ item.file_name }}</span>
<span class="artifact-meta">
<span>{{ formatArtifactSize(item.file_size) }}</span>
<span class="artifact-meta-sep">·</span>
<span>{{ formatArtifactDateTime(item.created_at) }}</span>
</span>
</span>
</button>
<t-button
class="artifact-download"
variant="text"
shape="square"
size="small"
:title="$t('agent.artifactDrawer.download')"
:aria-label="$t('agent.artifactDrawer.download')"
:loading="isDownloading(item)"
@click.stop="handleDownload(item)"
>
<template #icon>
<t-icon name="download" size="16px" />
</template>
</t-button>
<t-button
class="artifact-download artifact-delete"
variant="text"
shape="square"
size="small"
:title="$t('agent.artifactDrawer.delete')"
:aria-label="$t('agent.artifactDrawer.delete')"
:loading="isDeleting(item)"
@click.stop="handleDelete(item)"
>
<template #icon>
<t-icon name="delete" size="16px" />
</template>
</t-button>
</li>
</ul>
</template>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { MessagePlugin } from 'tdesign-vue-next'
import { deleteMessageArtifact, downloadArtifact } from '@/api/chat'
import { resolveFilePreviewExt } from '@/utils/filePreview'
import {
formatArtifactDateTime,
formatArtifactSize,
type SessionArtifactItem,
} from '@/utils/sessionArtifacts'
import { useChatSandboxPanel, type ArtifactPanelFocusState } from '@/composables/useChatSandboxPanel'
import { useConfirmDelete } from '@/components/settings/useConfirmDelete'
import DocumentPreview from '@/components/document-preview.vue'
import ArtifactFileIcon from './ArtifactFileIcon.vue'
const props = withDefaults(
defineProps<{
sessionId: string
items: SessionArtifactItem[]
collecting?: boolean
active?: boolean
}>(),
{
collecting: false,
active: true,
},
)
// The list is a computed over the loaded history, so the panel reports the
// delete upward instead of mutating its own prop.
const emit = defineEmits<{ (e: 'deleted', payload: { messageId: string; index: number }): void }>()
const { t } = useI18n()
const panel = useChatSandboxPanel()
const confirmDelete = useConfirmDelete()
const previewActions = ref<HTMLElement | null>(null)
const listRef = ref<HTMLElement | null>(null)
const previewItem = ref<SessionArtifactItem | null>(null)
const downloading = reactive<Record<string, boolean>>({})
const deleting = reactive<Record<string, boolean>>({})
const focusedMessageId = ref<string | null>(null)
const scope = ref<'current' | 'all'>('all')
const searchQuery = ref('')
const currentItems = computed(() => props.items.filter((item) => item.messageId === focusedMessageId.value))
const visibleItems = computed(() => {
const items = scope.value === 'current' ? currentItems.value : props.items
const query = searchQuery.value.trim().toLocaleLowerCase()
return query ? items.filter((item) => item.file_name.toLocaleLowerCase().includes(query)) : items
})
const previewFileType = computed(() => {
const item = previewItem.value
if (!item) return ''
return resolveFilePreviewExt(item.file_name, item.file_type)
})
function downloadKey(item: SessionArtifactItem): string {
return `${item.messageId}:${item.index}`
}
function isDownloading(item: SessionArtifactItem): boolean {
return !!downloading[downloadKey(item)]
}
function isDeleting(item: SessionArtifactItem): boolean {
return !!deleting[downloadKey(item)]
}
// Each row here is one regeneration of a file, so the delete takes just that
// version. The artifact library, which folds versions into one entry, is where
// deleting the whole file lives.
function handleDelete(item: SessionArtifactItem) {
if (isDeleting(item)) return
confirmDelete({
title: t('agent.artifactDrawer.deleteTitle'),
body: t('agent.artifactDrawer.deleteConfirm', { name: item.file_name }),
onConfirm: () => performDelete(item),
})
}
async function performDelete(item: SessionArtifactItem) {
if (!props.sessionId || !item.messageId) {
MessagePlugin.error(t('agent.artifactDrawer.deleteFailed'))
return
}
const key = downloadKey(item)
deleting[key] = true
try {
await deleteMessageArtifact(props.sessionId, item.messageId, item.index)
if (previewItem.value && downloadKey(previewItem.value) === key) previewItem.value = null
emit('deleted', { messageId: item.messageId, index: item.index })
MessagePlugin.success(t('agent.artifactDrawer.deleted'))
} catch (err) {
console.error('[ChatArtifactsPanel] delete failed:', err)
MessagePlugin.error(t('agent.artifactDrawer.deleteFailed'))
} finally {
deleting[key] = false
}
}
function findItem(messageId: string, previewIndex?: number | null): SessionArtifactItem | undefined {
if (previewIndex != null && Number.isInteger(previewIndex)) {
return props.items.find((item) => item.messageId === messageId && item.index === previewIndex)
}
return props.items.find((item) => item.messageId === messageId)
}
function applyFocus(focus: ArtifactPanelFocusState | null | undefined) {
if (!focus?.messageId) return
focusedMessageId.value = focus.messageId
const wantsPreview = focus.previewIndex != null && Number.isInteger(focus.previewIndex)
if (wantsPreview) {
const target = findItem(focus.messageId, focus.previewIndex)
if (target) previewItem.value = target
return
}
previewItem.value = null
void nextTick(() => {
const container = listRef.value
if (!container) return
const rows = container.querySelectorAll<HTMLElement>('[data-message-id]')
for (const row of rows) {
if (row.getAttribute('data-message-id') === focus.messageId) {
// Keep positioning inside the list: scrollIntoView can also scroll the
// outer page horizontally while the fixed panel is sliding into view.
const itemRect = row.getBoundingClientRect()
const containerRect = container.getBoundingClientRect()
let nextTop: number | null = null
if (itemRect.top < containerRect.top) {
nextTop = container.scrollTop + itemRect.top - containerRect.top
} else if (itemRect.bottom > containerRect.bottom) {
nextTop = container.scrollTop + itemRect.bottom - containerRect.bottom
}
if (nextTop !== null) {
container.scrollTo({ top: Math.max(0, nextTop), behavior: 'instant' })
}
break
}
}
})
}
watch(
() => panel?.artifactFocus.value,
(focus) => {
scope.value = focus?.messageId ? 'current' : 'all'
searchQuery.value = ''
applyFocus(focus)
},
{ immediate: true },
)
watch(
() => props.sessionId,
() => {
previewItem.value = null
focusedMessageId.value = null
scope.value = 'all'
searchQuery.value = ''
panel?.clearArtifactFocus()
},
)
watch(
() => props.items,
(items) => {
const current = previewItem.value
if (current) {
const next = items.find(
(item) => item.messageId === current.messageId && item.index === current.index,
)
if (!next) previewItem.value = null
return
}
if (scope.value === 'current' && !searchQuery.value.trim()) {
applyFocus(panel?.artifactFocus.value)
}
},
)
function openPreview(item: SessionArtifactItem) {
previewItem.value = item
}
function closePreview() {
previewItem.value = null
}
async function handleDownload(item: SessionArtifactItem) {
if (!props.sessionId || !item.messageId) {
MessagePlugin.error(t('agent.artifactDrawer.downloadFailed'))
return
}
const key = downloadKey(item)
downloading[key] = true
try {
const blob = await downloadArtifact(props.sessionId, item.messageId, item.index)
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = item.file_name || 'artifact'
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
setTimeout(() => URL.revokeObjectURL(url), 1000)
} catch (err) {
console.error('[ChatArtifactsPanel] download failed:', err)
MessagePlugin.error(t('agent.artifactDrawer.downloadFailed'))
} finally {
downloading[key] = false
}
}
</script>
<style scoped lang="less">
@import '@/components/css/artifact-filter-tabs.less';
.chat-artifacts-panel {
flex: 1;
min-height: 0;
width: 100%;
display: flex;
flex-direction: column;
overflow: hidden;
}
.artifact-panel-header {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
padding: 8px 12px;
border-bottom: 1px solid var(--td-component-stroke);
flex-shrink: 0;
}
.artifact-back {
flex-shrink: 0;
color: var(--td-text-color-secondary);
:deep(.t-button__icon) {
margin: 0;
}
}
.artifact-preview-actions {
flex-shrink: 0;
}
.artifact-panel-header-icon {
width: 26px;
height: 32px;
}
.artifact-panel-header-title {
min-width: 0;
flex: 1;
font-size: var(--app-text-md);
font-weight: 600;
line-height: 1.4;
color: var(--td-text-color-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.artifact-preview-body {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
padding: 8px;
}
.artifact-panel-empty {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
padding: 32px 16px;
color: var(--td-text-color-placeholder);
font-size: var(--app-text-md);
text-align: center;
}
.artifact-panel-banner {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 14px;
font-size: var(--app-text-sm);
color: var(--td-text-color-secondary);
border-bottom: 1px solid var(--td-component-stroke);
}
.artifact-panel-banner-spin {
animation: wk-spin 0.8s linear infinite;
}
.artifact-list {
margin: 0;
padding: 0 4px 12px;
list-style: none;
overflow: auto;
flex: 1;
min-height: 0;
}
.artifact-item {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 8px;
border-radius: var(--app-radius-md);
&.is-previewable {
cursor: pointer;
}
&:hover {
background: var(--td-bg-color-container-hover);
}
}
.artifact-filters {
flex-shrink: 0;
display: flex;
flex-direction: column;
gap: 12px;
padding: 16px 12px 12px;
}
.artifact-scope {
.artifact-filter-tabs();
align-self: flex-start;
button {
display: inline-flex;
align-items: center;
gap: 8px;
span {
color: inherit;
opacity: 0.7;
font-size: var(--app-text-sm);
font-variant-numeric: tabular-nums;
}
}
}
.artifact-search :deep(.t-input) {
border-radius: 7px;
}
.artifact-body {
flex: 1;
min-width: 0;
}
.artifact-open {
flex: 1;
min-width: 0;
display: flex;
align-items: center;
gap: 12px;
padding: 0;
border: 0;
border-radius: var(--app-radius-xs);
background: transparent;
color: inherit;
font: inherit;
text-align: left;
cursor: pointer;
&:focus-visible {
outline: 2px solid var(--td-text-color-secondary);
outline-offset: 4px;
}
}
.artifact-name {
display: block;
font-size: var(--app-text-md);
font-weight: 500;
letter-spacing: 0.01em;
line-height: 1.35;
color: var(--td-text-color-primary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.artifact-meta {
margin-top: 2px;
font-size: var(--app-text-sm);
line-height: 1.3;
color: var(--td-text-color-placeholder);
display: flex;
align-items: center;
gap: 4px;
}
.artifact-meta-sep {
opacity: 0.6;
}
.artifact-download.t-button {
flex-shrink: 0;
width: 30px;
height: 30px;
border-radius: 7px;
color: var(--td-text-color-secondary);
transition: background-color var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
&:not(.t-is-disabled):not(.t-is-loading):hover {
background: color-mix(in srgb, var(--td-text-color-primary) 10%, var(--td-bg-color-container));
color: var(--td-text-color-primary);
}
&:not(.t-is-disabled):not(.t-is-loading):active {
background: color-mix(in srgb, var(--td-text-color-primary) 16%, var(--td-bg-color-container));
}
&:focus-visible {
outline: 2px solid var(--td-text-color-secondary);
outline-offset: 2px;
}
&.artifact-delete:not(.t-is-disabled):not(.t-is-loading):hover {
background: var(--td-error-color-1);
color: var(--td-error-color);
}
:deep(.t-button__icon) {
margin: 0;
}
}
</style>
@@ -0,0 +1,216 @@
<template>
<div
class="chat-memory-step"
:class="variant === 'root'
? 'memory-root'
: ['tree-child', 'memory-step', { 'tree-child-last': isLast }]"
>
<div
class="memory-header"
role="button"
tabindex="0"
:aria-expanded="expanded"
@click="emit('toggle')"
@keydown.enter.prevent="emit('toggle')"
@keydown.space.prevent="emit('toggle')"
>
<ChatTimelineIcon v-if="variant !== 'root'" class="memory-icon" name="bookmark" />
<span class="memory-name">{{ t('chat.memoryUsedCount', { count: memories.length }) }}</span>
<ChatTimelineIcon width="14" height="14" class="memory-chevron" :name="expanded ? 'chevron-down' : 'chevron-right'" />
</div>
<div v-if="expanded" class="memory-detail-content">
<div v-for="memory in memories" :key="memory.id" class="memory-row">
<span class="memory-kind">{{ memoryKindLabel(memory.kind) }}</span>
<span class="memory-text">{{ memory.content }}</span>
<button
type="button"
class="memory-forget"
:disabled="forgettingId === memory.id"
:title="t('chat.memoryForget')"
@click.stop="emit('forget', memory)"
>
<t-icon name="delete" />
</button>
</div>
<p class="memory-hint">{{ t('chat.memoryHint') }}</p>
</div>
</div>
</template>
<script setup lang="ts">
import ChatTimelineIcon from '@/components/ChatTimelineIcon.vue'
import { useI18n } from 'vue-i18n'
type Memory = { id: string; kind: string; content: string }
withDefaults(
defineProps<{
memories: Memory[]
expanded?: boolean
// A step sits inside an existing timeline; a root leads a turn that has no
// timeline of its own, so it lines up with the collapsed headers next to it
// instead of pretending to be a branch of something.
variant?: 'step' | 'root'
isLast?: boolean
forgettingId?: string
}>(),
{ variant: 'step' },
)
const emit = defineEmits<{
(event: 'toggle'): void
(event: 'forget', memory: Memory): void
}>()
const { t } = useI18n()
const MEMORY_KINDS = ['profile', 'preference', 'fact', 'task', 'interest'] as const
const memoryKindLabel = (kind: string) => {
if ((MEMORY_KINDS as readonly string[]).includes(kind)) {
return t(`memorySettings.kinds.${kind}`)
}
return t('memorySettings.kinds.fact')
}
</script>
<style scoped lang="less">
// Layout for the step variant comes from the host timeline's .tree-child rules,
// which reach this component through its root element. Everything inside it has
// to be styled here.
.memory-header {
position: relative;
display: flex;
align-items: center;
gap: 12px;
min-height: 24px;
cursor: pointer;
user-select: none;
&:focus-visible {
outline: none;
.memory-name, .memory-icon {
color: var(--td-text-color-primary);
}
}
}
.memory-icon {
position: absolute;
left: -42px;
top: 3px;
width: 18px;
height: 18px;
flex-shrink: 0;
color: var(--agent-step-icon-color, var(--td-text-color-secondary));
}
.memory-name {
font-size: var(--agent-step-text-size, 14px);
line-height: 1.55;
font-weight: 400;
color: var(--agent-step-color, var(--td-text-color-secondary));
word-break: break-word;
}
.memory-chevron {
flex-shrink: 0;
font-size: var(--app-text-md);
color: var(--agent-step-icon-color, var(--td-text-color-secondary));
}
.memory-root {
margin: 0;
.memory-header {
gap: 6px;
min-height: 22px;
line-height: 22px;
&:hover .memory-name {
color: var(--td-text-color-primary);
}
}
.memory-chevron {
font-size: var(--app-text-base);
color: currentColor;
}
}
.memory-detail-content {
width: 100%;
margin-top: 4px;
font-size: var(--agent-step-summary-size, 13px);
line-height: 1.55;
color: var(--agent-step-color, var(--td-text-color-secondary));
}
.memory-row {
display: flex;
width: 100%;
align-items: baseline;
gap: 8px;
padding: 2px 0;
}
// A plain label would run straight into the sentence ("个人信息在做医疗影像
// …"), so the kind reads as a tag rather than as the first words of the memory.
.memory-kind {
flex-shrink: 0;
padding: 0 6px;
border-radius: 3px;
background: var(--td-bg-color-secondarycontainer);
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
line-height: 18px;
}
.memory-text {
flex: 1 1 auto;
min-width: 0;
word-break: break-word;
}
.memory-forget {
flex: 0 0 auto;
margin-left: auto;
padding: 0;
border: 0;
outline: none;
background: transparent;
color: var(--td-text-color-placeholder);
font-size: var(--app-text-md);
line-height: 1;
cursor: pointer;
opacity: 0;
transition: opacity var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
&:focus-visible {
opacity: 1;
color: var(--td-error-color);
}
&:hover:not(:disabled) {
color: var(--td-error-color);
}
&:disabled {
cursor: default;
opacity: 0.5;
}
}
// Revealing the control on hover keeps the list readable as a list, while
// still putting delete one click away from the memory it belongs to.
.memory-row:hover .memory-forget {
opacity: 1;
}
.memory-hint {
margin: 6px 0 0;
color: var(--td-text-color-placeholder);
}
</style>
@@ -0,0 +1,173 @@
<template>
<div ref="viewport" class="child-stream" @scroll="onScroll">
<div class="child-stream-content">
<p v-if="loading && !messages.length">{{ t('common.loading') }}</p>
<div v-if="failure" class="child-stream-error" role="alert">
{{ failure }} <button type="button" @click="refresh">{{ t('common.retry') }}</button>
</div>
<template v-for="message in messages" :key="String(message.id)">
<details v-if="message.role === 'user'" class="child-assignment">
<summary>
<span class="child-assignment-label">
<ChatTimelineIcon class="child-assignment-icon" name="task" />
{{ t('agentStream.collaboration.assignment') }}
</span>
<span v-if="message === latestAssignment" class="child-assignment-status" :class="task.status" role="status">
<span class="child-assignment-dot" aria-hidden="true" />
{{ t(`agentStream.collaboration.status.${task.status}`) }}
</span>
<ChatTimelineIcon class="child-assignment-chevron" name="chevron-right" width="14" height="14" />
</summary>
<div class="child-assignment-body">{{ message.content }}</div>
</details>
<AgentStreamDisplay v-else-if="message.role === 'assistant'" :session="message" :session-id="task.sessionId" artifacts-in-drawer />
</template>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, defineAsyncComponent, nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import ChatTimelineIcon from '@/components/ChatTimelineIcon.vue'
import { useChatScrollFollow } from '@/composables/useChatScrollFollow'
import { getMessageList } from '@/api/chat'
import { useStream } from '@/api/chat/streame'
import { isAwaitingInput, useChatStreamHandler, type ChatMessage } from '@/composables/useChatStreamHandler'
import { isCollaborationTaskActive, type CollaborationTaskView } from '@/utils/collaborationDisplay'
const AgentStreamDisplay = defineAsyncComponent(() => import('./AgentStreamDisplay.vue'))
const props = defineProps<{ task: CollaborationTaskView; active?: boolean }>()
const { t } = useI18n()
const messages = reactive<ChatMessage[]>([])
const latestAssignment = computed(() => [...messages].reverse().find(message => message.role === 'user'))
const viewport = ref<HTMLElement | null>(null)
const loading = ref(false)
const isReplying = ref(false)
const currentAssistantMessageId = ref('')
const fullContent = ref('')
const failure = ref('')
let closed = false
let refreshing = false
let refreshRequested = false
let timer: ReturnType<typeof setTimeout> | undefined
const readingHistory = ref(false)
let historySignature = ''
const scrollFollow = useChatScrollFollow(viewport, readingHistory, computed(() => props.active !== false))
const { onScroll, scrollToBottom } = scrollFollow
let savedScrollTop = 0
watch(() => props.active, active => {
if (active === false) savedScrollTop = viewport.value?.scrollTop || 0
else void nextTick(() => {
if (viewport.value) {
viewport.value.scrollTop = readingHistory.value ? savedScrollTop : viewport.value.scrollHeight
scrollFollow.rememberPosition()
}
})
})
const stream = useStream()
const handler = useChatStreamHandler({ messagesList: messages, loading, isReplying,
currentAssistantMessageId, fullContent, isAgentStreamSession: () => true, scrollToBottom,
preserveIncompleteStreamReactive: true })
stream.onChunk(data => { if (!closed) handler.processStreamChunk(data) })
async function refresh() {
if (closed || refreshing || stream.isStreaming.value) return
clearTimeout(timer)
refreshing = true
loading.value = true
try {
const response = await getMessageList({ session_id: props.task.sessionId, limit: 100, created_at: '' })
if (closed) return
const rows = (response?.data || []) as ChatMessage[]
const signature = JSON.stringify(rows)
if (signature !== historySignature) {
messages.splice(0)
await handler.handleMsgList(rows)
historySignature = signature
}
failure.value = ''
// Suspended messages are settled for rendering, but may resume on the same
// message ID. Never mistake that presentation flag for a terminal task.
const latest = [...messages].reverse().find(m => m.role === 'assistant')
const waiting = isAwaitingInput(latest)
const pending = latest && (!latest.is_completed || waiting) ? latest : undefined
if (pending && (!waiting || props.task.status === 'running')) {
currentAssistantMessageId.value = String(pending.id)
if (waiting) handler.prepareResumedMessage(pending, String((pending.pending_prompt as any)?.id || ''))
await stream.startStream({ session_id: props.task.sessionId, query: String(pending.id),
method: 'GET', url: '/api/v1/sessions/continue-stream' })
if (!closed && stream.error.value) failure.value = stream.error.value
}
} catch (error: any) {
if (!closed) failure.value = error?.message || t('common.error')
} finally {
refreshing = false
loading.value = false
// Poll only while disconnected; token updates use the child SSE stream.
if (!closed && (refreshRequested || isCollaborationTaskActive(props.task.status))) {
timer = setTimeout(refresh, refreshRequested ? 0 : 2000)
}
refreshRequested = false
}
}
watch(() => props.task.status, () => {
if (refreshing) refreshRequested = true
else if (!stream.isStreaming.value) void refresh()
})
onMounted(refresh)
onUnmounted(() => { closed = true; clearTimeout(timer); stream.stopStream() })
</script>
<style scoped lang="less">
@import '../../../components/css/chat-scrollbar.less';
@import (reference) '@/components/css/chat-timeline-theme.less';
.child-stream { .chat-timeline-theme(); height: 100%; box-sizing: border-box; overflow-y: auto; overscroll-behavior-y: contain; padding: 18px 16px 24px; font-size: var(--app-text-base); .chat-scrollbar(); }
.child-assignment {
margin: 0 0 16px;
border-radius: var(--app-radius-md);
background: color-mix(in srgb, var(--td-text-color-primary) 3%, transparent);
}
.child-assignment summary {
display: flex;
align-items: center;
gap: 12px;
min-height: 36px;
padding: 6px 10px;
box-sizing: border-box;
border-radius: var(--app-radius-md);
color: var(--agent-step-color);
font-size: var(--agent-step-text-size, 14px);
line-height: 1.55;
list-style: none;
cursor: pointer;
transition: color var(--app-motion-fast) ease;
}
.child-assignment summary::-webkit-details-marker { display: none; }
.child-assignment summary:hover, .child-assignment[open] summary { color: var(--td-text-color-primary); }
.child-assignment summary:focus-visible { outline: 2px solid var(--td-brand-color); outline-offset: 2px; }
.child-assignment-label { display: inline-flex; align-items: center; gap: 12px; min-width: 0; }
.child-assignment-icon { flex-shrink: 0; color: inherit; }
.child-assignment-chevron { margin-left: auto; flex-shrink: 0; color: var(--td-text-color-placeholder); transition: transform var(--app-motion-fast) ease; }
.child-assignment[open] .child-assignment-chevron { transform: rotate(90deg); }
.child-assignment-status { display: inline-flex; align-items: center; gap: 6px; flex-shrink: 0; color: var(--td-text-color-placeholder); font-size: var(--agent-step-summary-size, 13px); }
.child-assignment-dot { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }
.child-assignment-status.running { color: var(--td-brand-color); }
.child-assignment-status.running .child-assignment-dot { animation: child-assignment-pulse 1.6s ease-out infinite; }
.child-assignment-status.waiting, .child-assignment-status.needs_attention { color: var(--td-warning-color); }
.child-assignment-status.failed { color: var(--td-error-color); }
.child-assignment-body {
margin: 0;
padding: 2px 12px 12px 40px;
white-space: pre-wrap;
overflow-wrap: anywhere;
color: var(--td-text-color-secondary);
font-size: var(--agent-step-summary-size, 13px);
line-height: 1.7;
}
@keyframes child-assignment-pulse {
0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--td-brand-color) 45%, transparent); }
100% { box-shadow: 0 0 0 6px transparent; }
}
@media (prefers-reduced-motion: reduce) {
.child-assignment-chevron, .child-assignment summary { transition: none; }
.child-assignment-status.running .child-assignment-dot { animation: none; }
}
.child-stream-error { color: var(--td-error-color); margin: 12px 0; }
</style>
@@ -0,0 +1,99 @@
<template>
<div ref="bar" class="child-agent-tabs" :class="{ 'in-header': headerMode }" role="tablist" :aria-label="t('agentStream.collaboration.tabs')">
<button type="button" role="tab" class="child-agent-tab child-agent-tab-parent" :class="{ 'is-active': !activeId }"
:aria-selected="!activeId" :tabindex="!activeId ? 0 : -1" @click="$emit('select', '')"
@keydown="navigate($event, 0)">
<span v-if="attention" class="child-agent-tab-dot waiting" :title="t('agentStream.collaboration.status.waiting')" />
<slot name="parent">{{ t('agentStream.collaboration.mainConversation') }}</slot>
</button>
<div class="child-agent-tabs-scroll">
<div v-for="(tab, index) in tabs" :key="tab.id" class="child-agent-tab-entry" :class="{ 'is-active': activeId === tab.id }">
<button type="button" role="tab" class="child-agent-tab" :aria-selected="activeId === tab.id"
:tabindex="activeId === tab.id ? 0 : -1" :title="`${tab.task.displayName} · ${t(`agentStream.collaboration.status.${tab.task.status}`)}`"
@click="$emit('select', tab.id)" @keydown="navigate($event, index + 1)">
<span class="child-agent-tab-dot" :class="tab.task.status" aria-hidden="true" />
<span class="child-agent-tab-name" :class="{ 'is-running': tab.task.status === 'running' }">{{ tab.task.displayName || t('agentStream.collaboration.unnamed') }}</span>
</button>
<button type="button" class="child-agent-tab-close" :aria-label="`${t('common.close')} ${tab.task.displayName}`"
@click="closeTab(tab.id)"><CloseIcon aria-hidden="true" /></button>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { nextTick, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { CloseIcon } from 'tdesign-icons-vue-next'
import type { CollaborationTaskView } from '@/utils/collaborationDisplay'
const props = defineProps<{ tabs: Array<{ id: string; task: CollaborationTaskView }>; activeId: string; attention?: boolean; headerMode?: boolean }>()
const emit = defineEmits<{ select: [id: string]; close: [id: string] }>()
const { t } = useI18n()
const bar = ref<HTMLElement>()
function closeTab(id: string) {
emit('close', id)
void nextTick(() => bar.value?.querySelector<HTMLButtonElement>('[aria-selected="true"]')?.focus())
}
function navigate(event: KeyboardEvent, index: number) {
const count = props.tabs.length + 1
let target: number
if (event.key === 'ArrowRight') target = (index + 1) % count
else if (event.key === 'ArrowLeft') target = (index + count - 1) % count
else if (event.key === 'Home') target = 0
else if (event.key === 'End') target = count - 1
else return
event.preventDefault()
emit('select', target === 0 ? '' : props.tabs[target - 1].id)
bar.value?.querySelectorAll<HTMLButtonElement>('[role="tab"]')[target]?.focus()
}
watch(() => props.activeId, () => nextTick(() => {
if (props.activeId) bar.value?.querySelector('.child-agent-tabs-scroll [aria-selected="true"]')?.scrollIntoView({ block: 'nearest', inline: 'nearest' })
}))
</script>
<style scoped lang="less">
.child-agent-tabs { display: flex; align-items: center; flex-shrink: 0; gap: 4px; padding: 6px 12px; border-bottom: 1px solid var(--td-component-border); min-width: 0; }
.child-agent-tabs-scroll { display: flex; align-items: center; gap: 4px; min-width: 0; overflow-x: auto; scrollbar-width: none; }
.child-agent-tabs-scroll::-webkit-scrollbar { display: none; }
.child-agent-tab-entry { display: flex; align-items: center; flex-shrink: 0; border-radius: var(--app-radius-sm); }
.child-agent-tab { display: flex; align-items: center; gap: 7px; padding: 7px 10px; border: 0; border-radius: var(--app-radius-sm); background: transparent; color: var(--td-text-color-secondary); font: inherit; font-size: var(--app-text-md); line-height: 1.4; white-space: nowrap; cursor: pointer; flex-shrink: 0; }
.child-agent-tabs.in-header { flex: 1; min-width: 0; border: 0; padding: 0; gap: 4px; }
.in-header .child-agent-tab { height: 28px; padding: 0 4px 0 10px; font-size: var(--app-text-sm, 13px); }
.in-header .child-agent-tab-entry { border-radius: var(--app-radius-md, 8px); }
.in-header .child-agent-tab-close { margin-right: 3px; }
.in-header .child-agent-tab-name { max-width: 130px; }
.child-agent-tab-name { max-width: 160px; overflow: hidden; text-overflow: ellipsis; }
.child-agent-tab.is-active, .child-agent-tab-entry.is-active { background: var(--td-bg-color-secondarycontainer); }
.child-agent-tab.is-active, .is-active .child-agent-tab { color: var(--td-text-color-primary); }
.child-agent-tab-entry { transition: background-color var(--app-motion-fast) ease; }
.child-agent-tab-entry:hover, .child-agent-tab-parent:hover { background: var(--td-bg-color-container-hover); }
.child-agent-tab-entry:hover .child-agent-tab, .child-agent-tab-close:hover { color: var(--td-text-color-primary); }
.in-header .child-agent-tab-parent { position: relative; padding: 0; gap: 4px; margin-right: 8px; background: transparent; color: var(--td-text-color-primary); }
.in-header .child-agent-tab-parent > .child-agent-tab-dot { position: absolute; right: 0; top: 0; }
.child-agent-tab:focus-visible, .child-agent-tab-close:focus-visible { outline: 2px solid var(--td-brand-color); outline-offset: -2px; }
.child-agent-tab-close { display: flex; align-items: center; justify-content: center; width: 22px; height: 22px; margin-right: 5px; padding: 0; border: 0; border-radius: var(--app-radius-xs); background: transparent; color: var(--td-text-color-placeholder); cursor: pointer; font-size: var(--app-text-sm); }
.child-agent-tab-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--td-text-color-placeholder); flex-shrink: 0; }
.child-agent-tab-dot.running { background: var(--td-brand-color); animation: child-tab-pulse 1.6s ease-out infinite; }
.child-agent-tab-dot.succeeded { background: var(--td-success-color); }
.child-agent-tab-name.is-running {
background: linear-gradient(90deg, currentColor 30%, var(--td-text-color-placeholder) 50%, currentColor 70%) 0 0 / 300% 100%;
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
animation: child-tab-shimmer 2.4s linear infinite;
}
.child-agent-tab-entry .child-agent-tab-close { opacity: 0; transition: opacity var(--app-motion-fast), color var(--app-motion-fast); }
.child-agent-tab-entry:hover .child-agent-tab-close, .child-agent-tab-entry.is-active .child-agent-tab-close, .child-agent-tab-close:focus-visible { opacity: 1; }
@keyframes child-tab-pulse {
0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--td-brand-color) 45%, transparent); }
100% { box-shadow: 0 0 0 5px transparent; }
}
@keyframes child-tab-shimmer {
from { background-position: 100% 0; }
to { background-position: 0 0; }
}
@media (prefers-reduced-motion: reduce) {
.child-agent-tab-dot.running, .child-agent-tab-name.is-running { animation: none; }
.child-agent-tab-name.is-running { background: none; -webkit-text-fill-color: currentColor; }
}
.child-agent-tab-dot.waiting, .child-agent-tab-dot.needs_attention { background: var(--td-warning-color); }
.child-agent-tab-dot.failed { background: var(--td-error-color); }
</style>
@@ -0,0 +1,58 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { parse, compileTemplate } from '@vue/compiler-sfc'
import { after, before, test } from 'node:test'
import { fileURLToPath } from 'node:url'
import { createServer, type ViteDevServer } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createSSRApp, h, type Component } from 'vue'
import { renderToString } from 'vue/server-renderer'
import { createI18n } from 'vue-i18n'
import zh from '../../../i18n/locales/zh-CN'
let server: ViteDevServer
let Card: Component
before(async () => {
server = await createServer({ configFile: false, optimizeDeps: { noDiscovery: true, entries: [] }, plugins: [vue()],
resolve: { alias: { '@': fileURLToPath(new URL('../../../', import.meta.url)) } },
server: { middlewareMode: true, hmr: false }, appType: 'custom' })
Card = (await server.ssrLoadModule('/src/views/chat/components/CollaborationTasks.vue')).default
// Compile the integration component as well: both timeline branches render progress.
const source = readFileSync(new URL('./AgentStreamDisplay.vue', import.meta.url), 'utf8')
const { descriptor } = parse(source)
const compiled = compileTemplate({ source: descriptor.template!.content, filename: 'AgentStreamDisplay.vue', id: 'test' })
assert.deepEqual(compiled.errors, [])
})
after(async () => { await server?.close() })
async function render(props: Record<string, unknown>) {
const app = createSSRApp({ render: () => h(Card, { toolLabel: () => '搜索网页', ...props }) })
app.use(createI18n({ legacy: false, locale: 'zh-CN', messages: { 'zh-CN': zh } }))
return renderToString(app)
}
test('child rows expose a readable task name and current tool without a top summary', async () => {
const html = await render({ task: { id: 'private-id', name: 'review', displayName: '审核任务',
sessionId: 's', runId: 'r', status: 'running', progress: { tool_name: 'web_search' } } })
assert.match(html, /审核任务/)
assert.match(html, /正在使用工具 · 搜索网页/)
assert.doesNotMatch(html, /collaboration-summary|private-id|<details/)
})
test('completed child rows hide obsolete running tool progress', async () => {
const html = await render({ task: { id: 'a', displayName: '检索', sessionId: 's', status: 'succeeded', progress: { tool_name: 'web_search' } } })
assert.match(html, /已完成/)
assert.doesNotMatch(html, /正在使用工具/)
})
test('only a running child animates its icon, and a sealed parent pauses it', async () => {
for (const status of ['running', 'queued', 'waiting', 'succeeded', 'failed', 'cancelled', 'interrupted']) {
const html = await render({ task: { id: 'a', displayName: '检索', sessionId: 's', status } })
const icon = html.match(/<svg[^>]*data-icon="agent"[^>]*>/)?.[0]
assert.ok(icon)
assert.equal(icon.includes('is-active'), status === 'running')
const disclosure = html.match(/<svg[^>]*data-icon="chevron-right"[^>]*>/)?.[0]
assert.ok(disclosure)
assert.doesNotMatch(disclosure, /is-active/)
}
const sealed = await render({
task: { id: 'a', displayName: '检索', sessionId: 's', status: 'running' }, motionPaused: true,
})
assert.doesNotMatch(sealed, /is-active/)
})
@@ -0,0 +1,124 @@
<template>
<button class="child-task-row" :class="{ 'is-running': task.status === 'running' }" type="button" :disabled="!task.sessionId || disabled" @click="$emit('open', task)">
<ChatTimelineIcon class="child-task-icon" name="agent" :active="task.status === 'running' && !motionPaused" />
<span class="child-task-name" :class="{ 'is-running': task.status === 'running' }">{{ task.displayName || t('agentStream.collaboration.unnamed') }}</span>
<span class="child-task-activity" :class="task.status">{{ activity }}</span>
<ChatTimelineIcon class="child-task-chevron" name="chevron-right" width="14" height="14" />
</button>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import ChatTimelineIcon from '@/components/ChatTimelineIcon.vue'
import type { CollaborationTaskView } from '@/utils/collaborationDisplay'
const props = defineProps<{ task: CollaborationTaskView; disabled?: boolean; motionPaused?: boolean; toolLabel: (name: string) => string }>()
defineEmits<{ open: [task: CollaborationTaskView] }>()
const { t } = useI18n()
const activity = computed(() => {
if (props.task.status === 'running' && props.task.progress?.tool_name) {
const phase = props.task.progress.phase
const key = ['tool_running', 'tool_succeeded', 'tool_failed'].includes(phase || '') ? phase : 'tool_running'
return `${t(`agentStream.collaboration.phase.${key}`)} · ${props.toolLabel(props.task.progress.tool_name)}`
}
return t(`agentStream.collaboration.status.${props.task.status}`)
})
</script>
<style scoped lang="less">
.child-task-row {
position: relative;
isolation: isolate;
display: flex;
align-items: center;
gap: 12px;
width: 100%;
min-height: 24px;
padding: 0;
border: 0;
background: transparent;
text-align: left;
font: inherit;
color: var(--agent-step-color, var(--td-text-color-secondary));
cursor: pointer;
&:hover:not(:disabled) {
.child-task-name, .child-task-icon { color: var(--td-text-color-primary); }
.child-task-chevron { opacity: 1; transform: translateX(1px); }
}
&:disabled { cursor: default; }
&:focus-visible { outline: 2px solid var(--td-brand-color); outline-offset: 2px; border-radius: var(--app-radius-sm, 4px); }
}
.child-task-icon {
width: 18px;
height: 18px;
flex-shrink: 0;
color: inherit;
}
.child-task-row.is-running {
&::before {
content: '';
position: absolute;
inset: -2px -6px;
z-index: -1;
border-radius: var(--app-radius-sm, 6px);
pointer-events: none;
background: linear-gradient(100deg,
transparent 30%,
color-mix(in srgb, var(--td-text-color-primary) 5%, transparent) 50%,
transparent 70%) 0 0 / 250% 100%;
animation: child-task-sweep 2.8s ease-in-out infinite;
}
}
.child-task-name {
flex: 0 1 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--agent-step-text-size, 14px);
line-height: 1.55;
transition: color var(--app-motion-fast);
}
.child-task-name.is-running {
background: linear-gradient(90deg,
var(--agent-step-color, var(--td-text-color-secondary)) 30%,
var(--td-text-color-primary) 50%,
var(--agent-step-color, var(--td-text-color-secondary)) 70%) 0 0 / 300% 100%;
-webkit-background-clip: text;
background-clip: text;
color: transparent;
animation: child-task-shimmer 2.4s linear infinite;
}
.child-task-activity {
flex-shrink: 0;
max-width: 50%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--td-text-color-placeholder);
font-size: var(--agent-step-summary-size, 13px);
line-height: 1.55;
}
.child-task-activity.waiting, .child-task-activity.needs_attention { color: var(--td-warning-color); }
.child-task-activity.failed { color: var(--td-error-color); }
.child-task-chevron {
flex-shrink: 0;
width: 14px;
margin-left: -6px;
color: var(--td-text-color-placeholder);
opacity: 0;
transition: opacity var(--app-motion-fast), transform var(--app-motion-fast);
}
.child-task-row:disabled .child-task-chevron { display: none; }
@keyframes child-task-shimmer {
from { background-position: 100% 0; }
to { background-position: 0 0; }
}
@keyframes child-task-sweep {
from { background-position: 100% 0; }
to { background-position: -50% 0; }
}
@media (prefers-reduced-motion: reduce) {
.child-task-name.is-running { animation: none; color: var(--agent-step-color, var(--td-text-color-secondary)); background: none; }
.child-task-row.is-running::before { display: none; }
.child-task-chevron { transition: none; }
}
</style>
@@ -0,0 +1,64 @@
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 cardSource = readFileSync(join(here, 'McpOAuthCard.vue'), 'utf8')
const settingsSource = readFileSync(join(here, '../../settings/components/McpServiceDialog.vue'), 'utf8')
const apiSource = readFileSync(join(here, '../../../api/mcp-service.ts'), 'utf8')
test('in-chat OAuth polling is bound to the newly opened authorization attempt', () => {
assert.match(cardSource, /authorization\.authorizationAttempt/)
assert.match(
cardSource,
/getMCPOAuthStatus\(props\.serviceId, authorization\.authorizationAttempt\)/,
)
assert.match(
cardSource,
/props\.serviceId,\s*authorization\.authorizationAttempt,\s*\)/,
)
})
test('settings OAuth polling cannot accept a pre-existing token as fresh authorization', () => {
assert.match(
settingsSource,
/getMCPOAuthStatus\(serviceId, authorization\.authorizationAttempt\)/,
)
})
test('in-chat OAuth success refreshes the caller MCP directory', () => {
assert.match(cardSource, /refreshMCPMetadata/)
assert.match(
cardSource,
/await resolveMCPOAuth\(props\.pendingId, \{ service_id: props\.serviceId, decision: 'authorize' \}\)/,
)
assert.match(cardSource, /await refreshMCPMetadata\(props\.serviceId\)/)
})
test('OAuth status API sends the attempt id to the backend', () => {
assert.match(apiSource, /authorization_attempt=\$\{encodeURIComponent\(authorizationAttempt\)\}/)
})
test('settings distinguishes refreshable tokens from usable authorization', () => {
assert.match(settingsSource, /getMCPOAuthAuthorizationStatus\(currentService\.value\.id\)/)
assert.match(settingsSource, /savedService\.value \?\? props\.service/)
assert.match(settingsSource, /oauthTokenState === 'refreshable'/)
assert.match(apiSource, /state: data\?\.state \?\? 'reauth_required'/)
})
test('settings wizard requires a synchronized directory before save', () => {
assert.match(settingsSource, /step === 1 && !toolsSynced/)
assert.match(settingsSource, /mcpMetadata\.syncRequired/)
assert.match(settingsSource, /formRef\.value\?\.validate\(\)/)
assert.match(settingsSource, /if \(valid !== true\) return null/)
})
test('tools step auto-fetches a missing directory without a banner CTA', () => {
const panelSource = readFileSync(join(here, '../../settings/components/McpMetadataPanel.vue'), 'utf8')
assert.match(panelSource, /if \(!saved && !props\.disabled\)/)
assert.match(panelSource, /refreshFrom\(current\)/)
assert.match(panelSource, /variant="text"/)
assert.doesNotMatch(panelSource, /t-alert/)
})
@@ -0,0 +1,308 @@
<template>
<div v-if="interactive" class="prompt-panel" @click.stop>
<div class="prompt-question">{{ $t('agentStream.mcpOAuth.dockQuestion', { target: targetLabel }) }}</div>
<div class="prompt-desc">{{ $t('agentStream.mcpOAuth.desc') }}</div>
<div class="prompt-footer">
<div class="prompt-footer-meta">
<span v-if="secondsLeft >= 0" class="action-timer" :class="timerClass">{{ formatCountdown(secondsLeft) }}</span>
</div>
<div class="prompt-footer-actions">
<button type="button" class="prompt-btn" :disabled="canceling || authorizing" @click="skip">
{{ $t('agentStream.mcpOAuth.skip') }}
</button>
<button type="button" class="prompt-btn is-primary" :disabled="authorizing || canceling" @click="authorize">
{{ $t('agentStream.mcpOAuth.authorize') }}<span class="prompt-btn-key" aria-hidden="true">↵</span>
</button>
</div>
</div>
</div>
<div v-else class="action-card interaction-inline" :class="{ 'action-pending': !resolved }">
<div class="action-header no-results">
<div class="action-title">
<ChatTimelineIcon class="action-title-icon" :name="headerIcon" :active="open" />
<span class="action-name">{{ mainTitle }}</span>
</div>
</div>
<div class="interaction-status-summary">
<div class="results-summary-text">
<template v-if="awaitingInDock">
<span class="status-label">{{ $t('agentStream.promptDock.waiting') }}</span>
<span class="inline-dot">·</span>
<button type="button" class="inline-action is-primary" @click.stop="dock?.focus(pendingId)">
{{ $t('agentStream.promptDock.handle') }}
</button>
</template>
<span v-else class="status-label">{{ statusLine }}</span>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import ChatTimelineIcon from '@/components/ChatTimelineIcon.vue'
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import {
cancelMCPOAuth,
getMCPOAuthAuthorizeURL,
getMCPOAuthStatus,
resolveMCPOAuth,
refreshMCPMetadata,
MCP_OAUTH_CALLBACK_PATH,
} from '@/api/mcp-service'
import {
cancelEmbedMCPOAuth,
getEmbedMCPOAuthAuthorizeURL,
getEmbedMCPOAuthStatus,
resolveEmbedMCPOAuth,
} from '@/api/embed'
import { markPromptSubmitted, promptSubmission, usePromptDock } from '@/composables/usePromptDock'
import { isSubmitKey } from '@/utils/promptKeys'
const props = defineProps<{
pendingId: string
// dock: the authorize prompt, shown above the composer. inline: the timeline row.
variant?: 'dock' | 'inline'
serviceId: string
serviceName: string
mcpToolName?: string
timeoutSeconds?: number
requestedAt?: number
resolved?: boolean
authorized?: boolean
resolveReason?: string
timedOut?: boolean
canceled?: boolean
embeddedMode?: boolean
embedChannelId?: string
embedToken?: string
embedSessionId?: string
embedSessionSig?: string
embedVisitorId?: string
}>()
const useEmbedOAuth = () =>
props.embeddedMode
&& props.embedChannelId
&& props.embedToken
&& props.embedSessionId
&& props.embedSessionSig
&& props.embedVisitorId
const { t } = useI18n()
const dock = usePromptDock()
const submission = computed(() => promptSubmission(props.pendingId))
const open = computed(() => !props.resolved && !submission.value)
// Without a dock (a view that does not provide one) the row stays answerable.
const interactive = computed(() => open.value && (props.variant === 'dock' || !dock))
const awaitingInDock = computed(() => open.value && props.variant !== 'dock' && Boolean(dock?.isDocked(props.pendingId)))
const authorizing = ref(false)
const canceling = ref(false)
const now = ref(Date.now())
let clock: number | null = null
let poll: number | null = null
const deadline = computed(() => {
const base = (props.requestedAt || 0) * 1000
const add = (props.timeoutSeconds || 600) * 1000
return base + add
})
const secondsLeft = computed(() => {
if (props.resolved) return -1
return Math.max(0, Math.floor((deadline.value - now.value) / 1000))
})
const timerClass = computed(() => {
if (secondsLeft.value <= 30) return 'timer-critical'
if (secondsLeft.value <= 120) return 'timer-warning'
return ''
})
const headerIcon = computed(() => {
if (!props.resolved) return 'lock-on'
if (props.authorized) return 'check-circle'
return 'close-circle'
})
const targetLabel = computed(() => (
props.mcpToolName
? t('agentStream.mcpOAuth.targetWithTool', { service: props.serviceName, tool: props.mcpToolName })
: props.serviceName
))
const mainTitle = computed(() => {
if (!props.resolved) {
return t('agentStream.mcpOAuth.waiting', { target: targetLabel.value })
}
return props.mcpToolName
? t('agentStream.mcpOAuth.titleWithTool', { service: props.serviceName, tool: props.mcpToolName })
: t('agentStream.mcpOAuth.titleWithService', { service: props.serviceName })
})
const statusLine = computed(() => {
if (!props.resolved) {
if (submission.value?.authorized) return t('agentStream.mcpOAuth.authorizedTag')
if (submission.value) return t('agentStream.mcpOAuth.canceledTag')
return t('agentStream.mcpOAuth.waitingStatus')
}
if (props.authorized) return t('agentStream.mcpOAuth.authorizedTag')
if (props.timedOut) return t('agentStream.mcpOAuth.timedOutTag')
return t('agentStream.mcpOAuth.canceledTag')
})
function formatCountdown(s: number): string {
if (s < 60) return t('agentStream.mcpOAuth.countdownShort', { seconds: s })
const m = Math.floor(s / 60)
const r = s % 60
return `${m}:${r.toString().padStart(2, '0')}`
}
function stopPoll() {
if (poll) {
window.clearInterval(poll)
poll = null
}
}
const skip = async () => {
if (props.resolved || canceling.value) return
canceling.value = true
try {
if (useEmbedOAuth()) {
await cancelEmbedMCPOAuth(
props.embedChannelId!,
props.embedToken!,
props.embedSessionId!,
props.embedSessionSig!,
props.embedVisitorId!,
props.pendingId,
)
} else {
await cancelMCPOAuth(props.pendingId)
}
markPromptSubmitted(props.pendingId, { authorized: false })
} catch (e: any) {
const msg = e?.response?.data?.error?.message || e?.message || t('agentStream.mcpOAuth.skipFailed')
MessagePlugin.error(msg)
} finally {
canceling.value = false
}
}
const authorize = async () => {
if (props.resolved || authorizing.value) return
authorizing.value = true
try {
const redirectUri = window.location.origin + MCP_OAUTH_CALLBACK_PATH
const frontendRedirect = useEmbedOAuth()
? window.location.pathname + window.location.search
: '/'
const authorization = useEmbedOAuth()
? await getEmbedMCPOAuthAuthorizeURL(
props.embedChannelId!,
props.embedToken!,
props.embedSessionId!,
props.embedSessionSig!,
props.embedVisitorId!,
props.serviceId,
{ redirect_uri: redirectUri, frontend_redirect: frontendRedirect },
)
: await getMCPOAuthAuthorizeURL(props.serviceId, {
redirect_uri: redirectUri,
frontend_redirect: frontendRedirect,
})
if (!authorization.authorizationUrl || !authorization.authorizationAttempt) {
MessagePlugin.error(t('agentStream.mcpOAuth.startFailed'))
authorizing.value = false
return
}
const popup = window.open(authorization.authorizationUrl, 'mcp_oauth', 'width=600,height=720')
poll = window.setInterval(async () => {
const closed = !popup || popup.closed
let ok = false
try {
ok = useEmbedOAuth()
? await getEmbedMCPOAuthStatus(
props.embedChannelId!,
props.embedToken!,
props.embedSessionId!,
props.embedSessionSig!,
props.embedVisitorId!,
props.serviceId,
authorization.authorizationAttempt,
)
: await getMCPOAuthStatus(props.serviceId, authorization.authorizationAttempt)
} catch {
/* transient; keep polling */
}
if (ok) {
stopPoll()
try { popup?.close() } catch { /* cross-origin close may throw */ }
try {
if (useEmbedOAuth()) {
await resolveEmbedMCPOAuth(
props.embedChannelId!,
props.embedToken!,
props.embedSessionId!,
props.embedSessionSig!,
props.embedVisitorId!,
props.pendingId,
{ service_id: props.serviceId, decision: 'authorize' },
)
} else {
await resolveMCPOAuth(props.pendingId, { service_id: props.serviceId, decision: 'authorize' })
try {
await refreshMCPMetadata(props.serviceId)
} catch {
/* next describe/list will live-fill this user's directory */
}
}
markPromptSubmitted(props.pendingId, { authorized: true })
MessagePlugin.success(t('agentStream.mcpOAuth.authorizedToast'))
} catch (e: any) {
const msg = e?.response?.data?.error?.message || e?.message || t('agentStream.mcpOAuth.resumeFailed')
MessagePlugin.error(msg)
}
authorizing.value = false
} else if (closed) {
stopPoll()
authorizing.value = false
}
}, 1500)
} catch (e: any) {
const msg = e?.response?.data?.error?.message || e?.message || t('agentStream.mcpOAuth.startFailed')
MessagePlugin.error(msg)
authorizing.value = false
}
}
onMounted(() => {
clock = window.setInterval(() => {
now.value = Date.now()
}, 1000)
})
onBeforeUnmount(() => {
if (clock) window.clearInterval(clock)
stopPoll()
})
/** Enter starts authorization while docked. */
const handleKey = (e: KeyboardEvent): boolean => {
if (!interactive.value || !isSubmitKey(e) || authorizing.value || canceling.value) return false
void authorize()
return true
}
defineExpose({ handleKey })
</script>
<style scoped lang="less">
@import './agent-interaction-card.less';
</style>
@@ -0,0 +1,87 @@
import assert from 'node:assert/strict'
import { after, before, test } from 'node:test'
import { fileURLToPath } from 'node:url'
import { createServer, type ViteDevServer } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createSSRApp, h, type Component } from 'vue'
import { renderToString } from 'vue/server-renderer'
import { createI18n } from 'vue-i18n'
import en from '../../../i18n/locales/en-US'
let server: ViteDevServer
let Renderer: Component
before(async () => {
server = await createServer({
configFile: false, optimizeDeps: { noDiscovery: true, entries: [] }, plugins: [
{
name: 'isolate-mcp-renderer',
enforce: 'pre',
load(id) {
// Unused result components depend on browser-only app services.
// Keep the real renderer, MCP component and shared result rows.
if (id.endsWith('.vue') && !['ToolResultRenderer.vue', 'McpToolResult.vue', 'ResultRow.vue'].some((name) => id.endsWith(`/${name}`))) {
return '<template><div /></template>'
}
},
},
vue(),
],
resolve: { alias: { '@': fileURLToPath(new URL('../../../', import.meta.url)) } },
server: { middlewareMode: true }, appType: 'custom',
})
Renderer = (await server.ssrLoadModule('/src/views/chat/components/ToolResultRenderer.vue')).default
})
after(async () => { await server?.close() })
async function render(props: Record<string, unknown>) {
const app = createSSRApp({ render: () => h(Renderer, props) })
app.use(createI18n({ legacy: false, locale: 'en-US', messages: { 'en-US': en } }))
app.component('t-icon', { render: () => h('span') })
app.component('t-popup', { render: () => h('span') })
return renderToString(app)
}
test('discovery renders tool rows instead of raw metadata, including old history', async () => {
const html = await render({ displayType: 'mcp_discovery', success: true, output: JSON.stringify({
mode: 'list_tools', server_name: 'Svrlog Mcp Server',
tools: [{ name: 'get_log', description: '<script>alert(1)</script>', tool_ref: 'mcpt_old' }],
total: 3, has_more: true, notice: 'external',
}) })
assert.match(html, /get_log/)
assert.match(html, /Svrlog Mcp Server/)
assert.match(html, /Showing 1 of 3/)
assert.match(html, /More results available/)
assert.match(html, /&lt;script&gt;/)
assert.doesNotMatch(html, /fallback-output|mcpt_old|<script>/)
})
test('definition renders parameters and expandable complete schema', async () => {
const html = await render({ displayType: 'mcp_discovery', output: JSON.stringify({
name: 'get_log', server_name: 'Svrlog Mcp Server',
input_schema: { type: 'object', required: ['start_time'], properties: { start_time: { type: 'string' } } },
}) })
assert.match(html, /start_time/)
assert.match(html, /Svrlog Mcp Server/)
assert.match(html, /Required/)
assert.match(html, /<details/)
assert.match(html, /Full parameter definition/)
assert.doesNotMatch(html, /fallback-output/)
})
test('proxy validation errors and empty service lists use dedicated views', async () => {
const error = await render({ displayType: 'mcp_call', success: false, output: 'arguments must be an object' })
assert.match(error, /role="alert"/)
assert.match(error, /arguments must be an object/)
assert.doesNotMatch(error, /fallback-output/)
const empty = await render({ displayType: 'mcp_discovery', output: '{"mode":"list_servers","total":0,"has_more":false}' })
assert.match(empty, /Showing 0 of 0/)
assert.doesNotMatch(empty, /fallback-output/)
const live = await render({
displayType: 'mcp_discovery',
success: true,
output: JSON.stringify({ mode: 'list_tools', tools: [{ name: 'get_log' }], total: 1 }),
toolData: { tool_name: 'discover_mcp_tools', success: true, output: '{"mode":"list_tools"}', error: '' },
})
assert.match(live, /get_log/)
assert.doesNotMatch(live, /fallback-output/)
})
@@ -0,0 +1,106 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { runInNewContext } from 'node:vm'
import test from 'node:test'
import { compileScript, parse } from '@vue/compiler-sfc'
import * as vue from 'vue'
import { createMemoryHistory, createRouter } from 'vue-router'
import ts from 'typescript'
import * as pageLink from '../../../utils/assistantPageLink'
const { descriptor } = parse(readFileSync(new URL('./OpenPageCard.vue', import.meta.url), 'utf8'))
const script = compileScript(descriptor, { id: 'open-page-card-test' }).content
function setup(link: unknown, initialPath = '/platform/knowledge-bases') {
const pushed: unknown[] = []
const drafts: unknown[] = []
const exports: any = {}
const resolver = createRouter({ history: createMemoryHistory(), routes: [{ path: '/:pathMatch(.*)*', component: {} }] })
const currentRoute = vue.shallowRef(resolver.resolve(initialPath))
const router = {
currentRoute,
resolve: resolver.resolve,
push: async (to: any) => {
pushed.push(to)
currentRoute.value = resolver.resolve(to)
},
}
runInNewContext(ts.transpileModule(script, {
compilerOptions: { module: ts.ModuleKind.CommonJS },
}).outputText, {
exports,
require: (name: string) => ({
vue,
'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
'vue-router': { useRouter: () => router },
'@/stores/assistant': { useAssistantStore: () => ({ setPageDraft: (d: unknown) => drafts.push(d) }) },
'@/utils/assistantPageLink': pageLink,
} as Record<string, unknown>)[name],
})
const state = exports.default.setup({ link }, { expose() {} })
return { state, pushed, drafts, router }
}
test('an automation link uses the clock icon', () => {
const { state } = setup({ display_type: 'open_page', page: 'automations', label: 'Automations', detail: 'Remind me' })
assert.equal(state.icon.value, 'time')
})
test('opening a new-model link hands its form to the page, then navigates', () => {
const { state, pushed, drafts } = setup({
display_type: 'open_page', page: 'settings_models', label: 'Models',
model_draft: { type: 'chat', base_url: 'https://api.example/v1' },
})
assert.equal(state.icon.value, 'control-platform')
assert.equal(state.endpoint.value, 'https://api.example/v1')
state.open()
assert.equal(JSON.stringify(drafts), JSON.stringify([{ kind: 'model', draft: { type: 'chat', base_url: 'https://api.example/v1' } }]))
assert.equal(JSON.stringify(pushed), JSON.stringify([{ path: '/platform/settings', query: { section: 'models' } }]))
})
test('a plain link clears any waiting form', () => {
const { state, pushed, drafts } = setup({
display_type: 'open_page', page: 'agent_editor', label: 'Bot', agent_id: 'a', section: 'knowledge',
})
state.open()
assert.deepEqual(drafts, [null], 'a stale draft must not open on another page')
assert.equal(JSON.stringify(pushed), JSON.stringify([{ path: '/platform/agents', query: { edit: 'a', section: 'knowledge' } }]))
})
test('one action toggles between returning from the assistant-opened page and opening it again', () => {
const { state, router, drafts } = setup({
display_type: 'open_page', page: 'settings', section: 'system', label: 'Settings',
navigated: true, return_path: '/platform/agents',
}, '/platform/settings?section=system')
assert.equal(state.actionLabel.value, 'agentStream.openPage.back')
state.activate()
assert.equal(router.currentRoute.value.fullPath, '/platform/agents')
assert.equal(state.actionLabel.value, 'agentStream.openPage.open')
assert.deepEqual(drafts, [], 'returning must not set a page draft')
state.activate()
assert.equal(router.currentRoute.value.fullPath, '/platform/settings?section=system')
assert.equal(state.actionLabel.value, 'agentStream.openPage.back')
})
test('manual opening remembers the current page and the label follows navigation elsewhere', async () => {
const { state, router } = setup({ display_type: 'open_page', page: 'settings', section: 'system', label: 'Settings' })
assert.equal(state.canReturn.value, false)
state.activate()
assert.equal(state.canReturn.value, true)
state.activate()
assert.equal(router.currentRoute.value.fullPath, '/platform/knowledge-bases')
await router.push('/platform/settings?section=models')
assert.equal(state.canReturn.value, false, 'another settings section is not the target')
state.activate()
state.activate()
assert.equal(router.currentRoute.value.fullPath, '/platform/settings?section=models')
})
test('unsafe or identical return destinations do not turn the action into return', () => {
for (const return_path of ['//evil.example', '/platform/settings?section=system']) {
const { state } = setup({
display_type: 'open_page', page: 'settings', section: 'system', label: 'Settings', navigated: true, return_path,
}, '/platform/settings?section=system')
assert.equal(state.canReturn.value, false)
}
})
@@ -0,0 +1,256 @@
<template>
<button type="button" class="open-page-card" :disabled="!location" :title="actionLabel" @click.stop="activate" @keydown.stop>
<span class="open-page-card__main">
<span class="open-page-card__icon" aria-hidden="true"><t-icon :name="icon" size="18px" /></span>
<span class="open-page-card__body">
<span class="open-page-card__title">{{ link.detail || link.label }}</span>
<span v-if="meta" class="open-page-card__meta">{{ meta }}</span>
</span>
<span class="open-page-card__go">
<t-icon v-if="canReturn" name="rollback" size="14px" aria-hidden="true" />
<span>{{ actionLabel }}</span>
<t-icon v-if="!canReturn" name="chevron-right" size="14px" aria-hidden="true" />
</span>
</span>
<span v-if="link.note || endpoint || draft" class="open-page-card__extra">
<span v-if="link.note" class="open-page-card__note">{{ link.note }}</span>
<span v-if="endpoint" class="open-page-card__endpoint">
<span class="open-page-card__endpoint-label">{{ t('agentStream.openPage.endpoint') }}</span>
<code>{{ endpoint }}</code>
</span>
<span v-if="draft" class="open-page-card__hint">
<t-icon name="info-circle" />{{ t('agentStream.openPage.draftHint') }}
</span>
</span>
</button>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { useAssistantStore } from '@/stores/assistant'
import {
pageLinkDraft,
pageLinkEndpoint,
pageLinkLocation,
pageLinkReturnPath,
type AssistantPageLink,
} from '@/utils/assistantPageLink'
const props = defineProps<{ link: AssistantPageLink }>()
const { t } = useI18n()
const router = useRouter()
const assistant = useAssistantStore()
const location = computed(() => pageLinkLocation(props.link))
const draft = computed(() => pageLinkDraft(props.link))
const endpoint = computed(() => pageLinkEndpoint(props.link))
const openedFrom = ref('')
const returnPath = computed(() => openedFrom.value || pageLinkReturnPath(props.link))
const atTarget = computed(() => {
if (!location.value) return false
const target = router.resolve(location.value)
const current = router.currentRoute.value
return current.path === target.path
&& Object.entries(target.query).every(([key, value]) => current.query[key] === value)
})
const canReturn = computed(() => atTarget.value && !!returnPath.value
&& router.resolve(returnPath.value).fullPath !== router.currentRoute.value.fullPath)
const actionLabel = computed(() => canReturn.value
? t('agentStream.openPage.back')
: draft.value ? t('agentStream.openPage.openForm') : t('agentStream.openPage.open'))
const meta = computed(() => {
const parent = props.link.detail ? props.link.label : ''
if (!props.link.navigated) return parent
return [t('agentStream.openPage.opened'), parent].filter(Boolean).join(' · ')
})
const icon = computed(() => {
switch (props.link.page) {
case 'agent_editor': return 'robot'
case 'settings_models': return 'control-platform'
case 'mcp_services': return 'tools'
case 'wiki': return 'book-open'
case 'settings': return props.link.section === 'system' ? 'info-circle' : 'setting-1'
case 'toolbox': return 'tools'
case 'agents': return 'robot'
case 'organizations': return 'usergroup'
case 'automations': return 'time'
default: return props.link.knowledge_id ? 'file' : 'folder'
}
})
function open() {
if (!location.value) return
if (!atTarget.value) openedFrom.value = router.currentRoute.value.fullPath
assistant.setPageDraft(draft.value)
void router.push(location.value)
}
function activate() {
if (canReturn.value) {
void router.push(returnPath.value)
} else {
open()
}
}
</script>
<style lang="less" scoped>
.open-page-card {
appearance: none;
display: flex;
flex-direction: column;
box-sizing: border-box;
width: 360px;
max-width: 100%;
margin-top: 8px;
padding: 0;
border: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-md);
background: var(--td-bg-color-secondarycontainer);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
font: inherit;
text-align: left;
color: inherit;
cursor: pointer;
transition: background var(--app-motion-fast) ease, border-color var(--app-motion-fast) ease;
&:hover:not(:disabled) {
background: var(--td-bg-color-secondarycontainer-hover);
border-color: var(--td-component-border);
.open-page-card__go {
color: var(--td-text-color-primary);
}
}
&:focus-visible {
outline: 2px solid var(--td-brand-color-focus);
outline-offset: 2px;
}
&:disabled {
cursor: default;
.open-page-card__go {
visibility: hidden;
}
}
}
.open-page-card__main {
display: flex;
align-items: center;
box-sizing: border-box;
gap: 10px;
width: 100%;
min-width: 0;
padding: 12px;
}
.open-page-card__icon {
display: inline-flex;
flex-shrink: 0;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
border-radius: var(--app-radius-sm);
background: var(--td-bg-color-container);
color: var(--td-text-color-secondary);
}
.open-page-card__body {
display: flex;
flex: 1;
flex-direction: column;
min-width: 0;
}
.open-page-card__title,
.open-page-card__meta {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.open-page-card__title {
color: var(--td-text-color-primary);
font-size: var(--app-text-base, 14px);
font-weight: 600;
line-height: 1.5;
}
.open-page-card__meta {
margin-top: 2px;
color: var(--td-text-color-placeholder);
font-size: var(--app-text-xs, 12px);
line-height: 1.5;
}
.open-page-card__go {
display: inline-flex;
flex-shrink: 0;
align-items: center;
gap: 2px;
color: var(--td-text-color-secondary);
font-size: var(--app-text-sm);
white-space: nowrap;
transition: color var(--app-motion-fast) ease;
}
.open-page-card__extra {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 6px;
margin: 0 12px;
padding: 8px 0 10px;
border-top: 1px solid var(--td-component-stroke);
font-size: var(--app-text-sm);
line-height: 1.5;
}
.open-page-card__note {
margin: 0;
color: var(--td-text-color-secondary);
overflow-wrap: anywhere;
}
.open-page-card__endpoint {
display: flex;
align-items: baseline;
gap: 4px;
max-width: 100%;
color: var(--td-text-color-placeholder);
code {
min-width: 0;
color: var(--td-text-color-secondary);
font-family: var(--app-font-family-mono);
overflow-wrap: anywhere;
}
}
.open-page-card__endpoint-label {
flex-shrink: 0;
}
.open-page-card__hint {
display: flex;
align-items: flex-start;
gap: 4px;
color: var(--td-text-color-placeholder);
.t-icon {
flex-shrink: 0;
margin-top: 3px;
}
}
</style>
@@ -0,0 +1,174 @@
<template>
<div class="page-edit-card" @click.stop @keydown.stop>
<div class="page-edit-card__header">
<span class="page-edit-card__icon" aria-hidden="true"><t-icon name="edit-1" size="18px" /></span>
<div class="page-edit-card__heading">
<div v-if="fill.location" class="page-edit-card__eyebrow">{{ fill.location }}</div>
<div class="page-edit-card__title">
{{ undone ? t('agentStream.pageEdit.undone') : t('agentStream.pageEdit.title', { count: applied.length }) }}
</div>
</div>
<t-button v-if="undoable" class="page-edit-card__action" size="small" variant="outline" :loading="undoing"
@click="undo">
<template #icon><t-icon name="rollback" /></template>
{{ t('agentStream.pageEdit.undo') }}
</t-button>
</div>
<ul v-if="applied.length && !undone" class="page-edit-card__list">
<li v-for="item in applied" :key="item.ref">
<span class="page-edit-card__label">{{ item.label || item.ref }}</span>
<span class="page-edit-card__summary">{{ item.summary }}</span>
</li>
</ul>
<div v-if="!undone" class="page-edit-card__footer">
<t-icon name="info-circle" />{{ t('agentStream.pageEdit.unsaved') }}
</div>
</div>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { MessagePlugin } from 'tdesign-vue-next'
import { canUndoFill, undoFill } from '@/utils/pageFill'
export interface PageFillResult {
location?: string
applied?: Array<{ ref: string; label?: string; summary?: string }>
}
const props = defineProps<{ fill: PageFillResult; toolCallId: string }>()
const { t } = useI18n()
const undoing = ref(false)
const undone = ref(false)
const applied = computed(() => props.fill.applied || [])
// Only this tab, before a reload, still holds what the fields held before.
const undoable = computed(() => !undone.value && canUndoFill(props.toolCallId))
async function undo() {
undoing.value = true
try {
const { restored, skipped } = await undoFill(props.toolCallId)
undone.value = restored > 0
if (skipped > 0) MessagePlugin.warning(t('agentStream.pageEdit.undoSkipped', { count: skipped }))
} finally {
undoing.value = false
}
}
</script>
<style lang="less" scoped>
.page-edit-card {
display: flex;
flex-direction: column;
gap: 8px;
box-sizing: border-box;
width: 360px;
max-width: 100%;
margin-top: 8px;
padding: 8px 10px 10px 8px;
border-radius: var(--app-radius-md);
background: var(--td-bg-color-secondarycontainer);
cursor: default;
}
.page-edit-card__header {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
}
.page-edit-card__icon {
display: inline-flex;
flex-shrink: 0;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
border-radius: var(--app-radius-md);
background: var(--td-bg-color-container);
color: var(--td-brand-color);
}
.page-edit-card__heading {
flex: 1;
min-width: 0;
}
.page-edit-card__eyebrow,
.page-edit-card__title {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.page-edit-card__eyebrow {
color: var(--td-text-color-placeholder);
font-size: var(--app-text-xs, 12px);
line-height: 18px;
}
.page-edit-card__title {
color: var(--td-text-color-primary);
font-size: var(--app-text-md);
font-weight: 500;
line-height: 1.35;
}
.page-edit-card__action {
flex-shrink: 0;
border-radius: var(--td-radius-medium);
}
.page-edit-card__list {
display: flex;
flex-direction: column;
gap: 4px;
margin: 0 0 0 2px;
padding: 0;
list-style: none;
font-size: var(--app-text-sm);
line-height: 1.6;
li {
display: flex;
gap: 8px;
min-width: 0;
}
}
.page-edit-card__label {
flex-shrink: 0;
max-width: 40%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--td-text-color-secondary);
}
.page-edit-card__summary {
min-width: 0;
color: var(--td-text-color-primary);
overflow-wrap: anywhere;
}
.page-edit-card__footer {
display: flex;
align-items: flex-start;
gap: 4px;
padding-top: 8px;
margin-left: 2px;
border-top: 1px solid var(--td-component-stroke);
color: var(--td-text-color-placeholder);
font-size: var(--app-text-xs, 12px);
line-height: 18px;
.t-icon {
flex-shrink: 0;
margin-top: 2px;
}
}
</style>
@@ -0,0 +1,288 @@
<template>
<transition name="prompt-dock">
<section v-if="dock && prompts.length" ref="root" class="prompt-dock" :class="{ 'is-collapsed': collapsed }"
tabindex="-1" :aria-label="title" @keydown="onKeydown">
<header class="prompt-dock__header" @click="collapsed && expand()">
<t-icon class="prompt-dock__icon" :name="icon" />
<span class="prompt-dock__title">{{ title }}</span>
<div class="prompt-dock__tools" @click.stop>
<div v-if="prompts.length > 1" class="prompt-dock__pager">
<button type="button" class="prompt-dock__btn" :disabled="index === 0"
:aria-label="$t('agentStream.promptDock.previous')" @click="step(-1)">
<t-icon name="chevron-left" />
</button>
<span class="prompt-dock__count">
{{ $t('agentStream.promptDock.pager', { current: index + 1, total: prompts.length }) }}
</span>
<button type="button" class="prompt-dock__btn" :disabled="index === prompts.length - 1"
:aria-label="$t('agentStream.promptDock.next')" @click="step(1)">
<t-icon name="chevron-right" />
</button>
</div>
<button type="button" class="prompt-dock__btn"
:aria-label="collapsed ? $t('agentStream.promptDock.expand') : $t('agentStream.promptDock.collapse')"
@click="collapsed ? expand() : (dock.collapsed.value = true)">
<t-icon :name="collapsed ? 'chevron-up' : 'remove'" />
</button>
</div>
</header>
<div v-show="!collapsed" class="prompt-dock__body">
<div v-for="prompt in prompts" v-show="prompt.pending_id === activeId" :key="prompt.pending_id">
<ToolApprovalCard v-if="prompt.type === 'tool_approval_required'" :ref="(el) => setCard(prompt, el)"
variant="dock" v-bind="{ ...timing(prompt), ...authProps }" :service-name="prompt.service_name || ''"
:mcp-tool-name="prompt.mcp_tool_name || ''" :description="prompt.description"
:delegated-task="prompt.delegated_task" :args-json="prompt.args_json" :grant-scope="prompt.grant_scope"
:grant-lapsed="prompt.grant_lapsed" />
<AskUserCard v-else-if="prompt.type === 'agent_prompt_required'" :ref="(el) => setCard(prompt, el)"
variant="dock" v-bind="{ ...timing(prompt), ...authProps }" :request="prompt.request" />
<McpOAuthCard v-else :ref="(el) => setCard(prompt, el)" variant="dock" v-bind="authProps"
:pending-id="prompt.pending_id" :service-id="prompt.service_id || ''"
:service-name="prompt.service_name || ''" :mcp-tool-name="prompt.mcp_tool_name || ''"
:timeout-seconds="prompt.timeout_seconds" :requested-at="prompt.requested_at" />
</div>
</div>
</section>
</transition>
</template>
<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { usePromptDock } from '@/composables/usePromptDock'
import { isTextEntry } from '@/utils/promptKeys'
import AskUserCard from './AskUserCard.vue'
import McpOAuthCard from './McpOAuthCard.vue'
import ToolApprovalCard from './ToolApprovalCard.vue'
const props = defineProps<{
embeddedMode?: boolean
embedChannelId?: string
embedToken?: string
embedSessionId?: string
embedSessionSig?: string
embedVisitorId?: string
}>()
type Prompt = Record<string, any>
type DockCard = { handleKey?: (e: KeyboardEvent) => boolean }
const { t } = useI18n()
const dock = usePromptDock()
const root = ref<HTMLElement | null>(null)
const cards = new Map<string, DockCard>()
const prompts = computed<Prompt[]>(() => dock?.prompts.value || [])
const collapsed = computed(() => Boolean(dock?.collapsed.value))
const activeId = computed(() => {
const chosen = dock?.activeId.value
return prompts.value.some((p) => p.pending_id === chosen) ? chosen : prompts.value[0]?.pending_id || ''
})
const index = computed(() => Math.max(0, prompts.value.findIndex((p) => p.pending_id === activeId.value)))
const active = computed(() => prompts.value[index.value])
const authProps = computed(() => ({
embeddedMode: props.embeddedMode,
embedChannelId: props.embedChannelId,
embedToken: props.embedToken,
embedSessionId: props.embedSessionId,
embedSessionSig: props.embedSessionSig,
embedVisitorId: props.embedVisitorId,
}))
const timing = (p: Prompt) => ({
pendingId: p.pending_id,
timeoutSeconds: p.timeout_seconds,
hotWaitSeconds: p.hot_wait_seconds,
suspendable: p.suspendable,
suspended: p.suspended,
expiresAt: p.expires_at,
requestedAt: p.requested_at,
})
const title = computed(() => {
switch (active.value?.type) {
case 'tool_approval_required': return t('agentStream.promptDock.approvalTitle')
case 'mcp_oauth_required': return t('agentStream.promptDock.oauthTitle')
default: return t('agentStream.askUser.title')
}
})
const icon = computed(() => {
switch (active.value?.type) {
case 'tool_approval_required': return 'secured'
case 'mcp_oauth_required': return 'lock-on'
default: return 'help-circle'
}
})
const setCard = (prompt: Prompt, el: unknown) => {
if (el) cards.set(prompt.pending_id, el as DockCard)
else cards.delete(prompt.pending_id)
}
const step = (delta: number) => {
const next = prompts.value[index.value + delta]
if (next && dock) dock.activeId.value = next.pending_id
}
const takeFocus = async () => {
await nextTick()
root.value?.focus({ preventScroll: true })
}
const expand = () => {
if (!dock) return
dock.collapsed.value = false
void takeFocus()
}
const onKeydown = (e: KeyboardEvent) => {
if (!dock) return
if (e.key === 'Escape') {
dock.collapsed.value = true
e.preventDefault()
return
}
if (collapsed.value) return
if (e.altKey && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) {
step(e.key === 'ArrowLeft' ? -1 : 1)
e.preventDefault()
return
}
if (cards.get(activeId.value)?.handleKey?.(e)) e.preventDefault()
}
watch(() => dock?.focusRequest.value, () => { void takeFocus() })
// A new prompt opens the dock; it takes focus unless the user is typing.
watch(() => prompts.value.map((p) => p.pending_id), (ids, previous = []) => {
const arrived = ids.filter((id) => !previous.includes(id))
if (!dock || !arrived.length) return
if (!ids.includes(dock.activeId.value)) dock.activeId.value = arrived[0]
dock.collapsed.value = false
if (!isTextEntry(document.activeElement)) void takeFocus()
})
</script>
<style scoped lang="less">
.prompt-dock {
width: 100%;
max-width: 960px;
margin: 0 auto 8px;
box-sizing: border-box;
background: var(--td-bg-color-container);
border: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-xl);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04), 0 8px 16px -4px rgba(0, 0, 0, 0.06);
outline: none;
transition: border-color var(--app-motion-fast) ease;
&:focus-within {
border-color: color-mix(in srgb, var(--td-brand-color) 45%, var(--td-component-stroke));
}
&.is-collapsed .prompt-dock__header {
padding-bottom: 6px;
cursor: pointer;
}
}
.prompt-dock__header {
display: flex;
align-items: center;
gap: 6px;
min-height: 34px;
padding: 6px 8px 0 14px;
box-sizing: border-box;
user-select: none;
}
.prompt-dock__icon {
flex-shrink: 0;
font-size: var(--app-text-base, 14px);
color: var(--td-text-color-placeholder);
}
.prompt-dock__title {
flex: 1;
min-width: 0;
font-size: var(--app-text-sm);
color: var(--td-text-color-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.prompt-dock__tools,
.prompt-dock__pager {
display: flex;
align-items: center;
gap: 2px;
flex-shrink: 0;
}
.prompt-dock__pager {
margin-right: 4px;
}
.prompt-dock__count {
min-width: 36px;
font-size: var(--app-text-sm);
font-variant-numeric: tabular-nums;
text-align: center;
color: var(--td-text-color-secondary);
}
.prompt-dock__btn {
appearance: none;
display: inline-flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
padding: 0;
border: 0;
border-radius: var(--app-radius-sm);
background: transparent;
font-size: var(--app-text-base, 14px);
color: var(--td-text-color-placeholder);
cursor: pointer;
transition: background var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
&:hover:not(:disabled) {
background: var(--td-bg-color-container-hover);
color: var(--td-text-color-primary);
}
&:disabled {
opacity: 0.35;
cursor: default;
}
}
.prompt-dock__body {
max-height: min(50vh, 440px);
overflow-y: auto;
padding: 6px 14px 12px;
overscroll-behavior: contain;
}
.prompt-dock-enter-active,
.prompt-dock-leave-active {
transition: opacity var(--app-motion-base) ease, transform var(--app-motion-base) ease;
}
.prompt-dock-enter-from,
.prompt-dock-leave-to {
opacity: 0;
transform: translateY(6px);
}
@media (prefers-reduced-motion: reduce) {
.prompt-dock-enter-active,
.prompt-dock-leave-active {
transition: none;
}
}
</style>
@@ -0,0 +1,102 @@
<template>
<div class="progress-updates">
<details v-if="earlier.length" class="progress-disclosure" @toggle="open = ($event.target as HTMLDetailsElement).open">
<summary>
<ChatTimelineIcon class="progress-icon" name="lightbulb" />
<span class="progress-text" :class="{ 'is-clamped': !open }">{{ open ? earlier[0] : content }}</span>
<span class="progress-count">{{ t('agentStream.collaboration.updates', { count: earlier.length + 1 }) }}</span>
<ChatTimelineIcon width="14" height="14" class="progress-chevron" name="chevron-right" />
</summary>
<ol class="progress-history">
<li v-for="(update, index) in later" :key="index">{{ update }}</li>
</ol>
</details>
<div v-else class="progress-summary">
<ChatTimelineIcon class="progress-icon" name="lightbulb" />
<span class="progress-text">{{ content }}</span>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import ChatTimelineIcon from '@/components/ChatTimelineIcon.vue'
const props = defineProps<{ content: string; history?: string[] }>()
const { t } = useI18n()
const open = ref(false)
const earlier = computed(() => props.history || [])
// Open, the updates read in time order like the rest of the timeline: the
// summary takes the first one and the list runs down to the latest.
const later = computed(() => [...earlier.value.slice(1), props.content])
</script>
<style scoped lang="less">
.progress-updates {
position: relative;
color: var(--agent-step-color, var(--td-text-color-secondary));
font: inherit;
font-size: var(--agent-step-summary-size, 13px);
line-height: 1.55;
overflow-wrap: anywhere;
}
.progress-summary, summary {
display: flex;
align-items: flex-start;
gap: 8px;
min-height: 24px;
padding: 0;
list-style: none;
&::-webkit-details-marker { display: none; }
}
.progress-text {
flex: 1;
min-width: 0;
&.is-clamped {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
}
summary {
cursor: pointer;
border-radius: var(--app-radius-xs);
&:hover .progress-count, &:hover .progress-chevron { color: var(--agent-step-color, var(--td-text-color-secondary)); }
&:focus-visible { outline: 2px solid var(--td-brand-color); outline-offset: 3px; }
}
.progress-count {
flex-shrink: 0;
color: var(--agent-step-color, var(--td-text-color-secondary));
font-size: var(--app-text-xs, 12px);
line-height: 20px;
white-space: nowrap;
transition: color var(--app-motion-fast);
}
.progress-chevron {
flex-shrink: 0;
margin-top: 3px;
color: var(--agent-step-color, var(--td-text-color-secondary));
transition: color var(--app-motion-fast), transform var(--app-motion-fast);
}
details[open] .progress-chevron { transform: rotate(90deg); }
.progress-icon {
position: absolute;
left: -42px;
top: 3px;
width: 18px;
height: 18px;
color: var(--agent-step-color, var(--td-text-color-secondary));
}
.progress-history {
display: flex;
flex-direction: column;
gap: 4px;
margin: 4px 0 0;
padding: 0;
list-style: none;
white-space: pre-wrap;
}
@media (prefers-reduced-motion: reduce) {
.progress-count, .progress-chevron { transition: none; }
}
</style>
@@ -0,0 +1,151 @@
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, 'RagPipelineProgress.vue'), 'utf8')
test('rag pipeline uses agent-style timeline structure', () => {
assert.match(source, /class="tree-children"/)
assert.match(source, /class="tree-child/)
assert.match(source, /getAgentToolIconName/)
assert.match(source, /name="check-circle"/)
assert.match(source, /streaming-loading-node/)
assert.match(source, /@import ['"]@\/components\/css\/chat-timeline-loading\.less['"]/)
assert.match(source, /search-results-summary-fixed/)
})
test('rag pipeline persists and collapses after the answer arrives', () => {
assert.match(source, /showCollapsedRoot/)
assert.match(source, /tree-root-status/)
assert.match(source, /collapsedStatusText/)
assert.match(source, /referenceSummaryText/)
assert.match(source, /hasThinking\.value/)
assert.match(source, /const visible = computed\([\s\S]*showPrePipelineWait\.value/)
})
test('rag pipeline toggles expand and collapse from the root header', () => {
assert.match(source, /class="tree-root-expand"/)
assert.match(source, /@click="toggleExpanded"/)
assert.match(source, /showExpandedTimeline \? 'chevron-down' : 'chevron-right'/)
assert.doesNotMatch(source, /refsExpanded \? 'chevron/)
assert.doesNotMatch(source, /tree-collapse-bar/)
})
test('only the collapsed root summary shows an expand chevron', () => {
const template = source.split('<script')[0]
assert.match(template, /tree-root-expand__icon/)
assert.equal((template.match(/tree-root-expand__icon/g) || []).length, 1)
})
test('rag pipeline opens references from search steps and the drawer composable', () => {
assert.match(source, /useChatReferencesDrawer/)
assert.match(source, /toggleReferencesDrawer/)
assert.match(source, /has-reference-trigger/)
assert.match(source, /handleStepClick/)
})
test('rag pipeline uses a native pending step and lets the thinking title shimmer while pending', () => {
assert.match(source, /showPrePipelineWait/)
assert.match(source, /v-else-if="showPrePipelineWait"[\s\S]*class="tool-event"/)
assert.match(source, /class="action-card action-pending"/)
assert.match(source, /t\('chat\.preparingAnswer'\)/)
assert.match(source, /showThinkingStep/)
assert.match(source, /'action-pending': thinkingPending/)
assert.match(source, /hasThinkingEvent/)
assert.doesNotMatch(source, /thinking-loading/)
assert.doesNotMatch(source, /showActivityIndicator/)
})
test('rag pipeline shows a pending model-answer step after retrieval completes', () => {
assert.match(source, /showWaitStep/)
assert.match(source, /getRagPipelineWaitKind/)
assert.match(source, /createRagWaitController/)
assert.match(source, /t\('chat\.connectingModelAndGeneratingAnswer'\)/)
assert.match(source, /t\('chat\.modelStillResponding'\)/)
assert.match(source, /rag-model-wait-step/)
assert.match(source, /'action-pending': !waitStepStalled/)
assert.match(source, /waitController\.dispose\(\)/)
})
test('rag pipeline announces wait status from a region that outlives each row', () => {
const template = source.split('<script')[0]
assert.match(template, /class="sr-only" role="status" aria-live="polite"/)
assert.equal((template.match(/aria-live/g) || []).length, 1)
assert.match(source, /liveStatusText/)
assert.match(source, /\.sr-only \{[\s\S]*clip: rect\(0, 0, 0, 0\)/)
})
test('done row appears only after the full turn completes', () => {
assert.match(source, /const showDoneRow = computed\(\(\) => \{[\s\S]*hasAnswer\.value/)
})
test('rag pipeline renders model thinking inside the timeline before the done row', () => {
assert.match(source, /rag-thinking-step/)
assert.match(source, /showThinkingStep/)
assert.match(source, /name="lightbulb"/)
const doneIndex = source.indexOf('agent-step-done')
const thinkingIndex = source.indexOf('rag-thinking-step')
assert.ok(doneIndex > -1 && thinkingIndex > -1)
assert.ok(thinkingIndex < doneIndex)
})
test('clickable timeline headers use pointer cursor', () => {
assert.match(source, /\.tool-event \{[\s\S]*\.action-header \{[\s\S]*cursor: pointer/)
assert.match(source, /\.action-header \{[\s\S]*&\.no-results \{[\s\S]*cursor: default/)
assert.match(source, /\.has-reference-trigger \{[\s\S]*cursor: pointer/)
})
test('collapsed summary uses compact spacing before the answer', () => {
assert.match(source, /\.tree-container \{\s*margin: 0 0 8px;/)
assert.match(source, /\.rag-pipeline-progress \{[\s\S]*margin: 0;/)
})
test('rag pipeline auto-scrolls capped thinking detail while streaming', () => {
assert.match(source, /isThinkingStreaming/)
assert.match(source, /scrollThinkingDetailToBottom/)
assert.match(source, /watch\(thinkingContent[\s\S]*scrollThinkingDetailToBottom/)
})
test('rag pipeline includes attachment prep steps on the timeline', () => {
assert.match(source, /RAG_TIMELINE_TOOL_NAMES/)
assert.match(source, /getAttachmentParsingSummaryHtml/)
assert.match(source, /isAttachmentTool/)
})
test('memory rides the existing timeline as a single reusable row', () => {
assert.match(source, /<ChatMemoryStep/)
assert.equal(source.split('<ChatMemoryStep').length - 1, 3)
assert.match(source, /:is-last="memoryIsLast"/)
})
// A host that draws its own timeline asks for the memory row only. Without the
// guard this component rebuilds a whole pipeline out of the same agent event
// stream, and the turn shows every retrieval step twice in two disjoint blocks.
test('memory-only hosts get the memory row and nothing else', () => {
assert.match(source, /memoryOnly\?: boolean/)
assert.match(source, /v-if="memoryOnly"\s*\n\s*variant="root"/)
assert.match(source, /<div v-else-if="showPrePipelineWait"/)
assert.match(source, /if \(props\.memoryOnly\) return hasMemory\.value/)
})
// The standalone row is for answers with no timeline at all. Agent turns keep
// their memory row inside the agent timeline, so rendering it here too would
// show the same recall twice, in two different visual languages.
test('only timeline-less answers get the standalone memory row', () => {
const botmsg = readFileSync(join(here, 'botmsg.vue'), 'utf8')
assert.match(
botmsg,
/<RagPipelineProgress v-if="!session\.isAgentMode && session\.used_memories\?\.length"[\s\S]*?memory-only/,
)
})
// Both timelines show the same row from the same state; duplicating the recall
// list, expand state and forget call is how the two drift apart.
test('memory row state is shared by both timelines', () => {
assert.match(source, /useChatMemoryRow\(\(\) => props\.session\?\.used_memories\)/)
const agent = readFileSync(join(here, 'AgentStreamDisplay.vue'), 'utf8')
assert.match(agent, /useChatMemoryRow\(/)
})
@@ -0,0 +1,833 @@
<template>
<div v-if="visible" ref="rootElement" class="rag-pipeline-progress">
<!-- Announcements need a region that outlives each wait row, otherwise screen
readers miss a live region that appears together with its own text. -->
<div class="sr-only" role="status" aria-live="polite">{{ liveStatusText }}</div>
<!-- A turn that only recalled memory has no pipeline to draw. It borrows
this component for the memory row alone, so anything derived from the
agent event stream must stay out of the way — the agent timeline is
rendering those same steps itself. -->
<ChatMemoryStep
v-if="memoryOnly"
variant="root"
:memories="memoryItems"
:expanded="memoryExpanded"
:forgetting-id="forgettingId"
@toggle="toggleMemory"
@forget="forgetMemory"
/>
<div v-else-if="showPrePipelineWait" class="tree-children">
<div class="tree-child tree-child-last streaming-loading-node">
<div class="tree-branch" />
<div class="tree-child-content">
<div class="tool-event">
<div class="action-card action-pending">
<div class="action-header no-results">
<div class="action-title">
<ChatTimelineIcon class="action-title-icon" name="lightbulb" :active="true" />
<span class="action-name">{{ t('chat.preparingAnswer') }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div v-else-if="!showCollapsedRoot" class="tree-children">
<ChatMemoryStep
v-if="hasMemory"
:memories="memoryItems"
:expanded="memoryExpanded"
:is-last="memoryIsLast"
:forgetting-id="forgettingId"
@toggle="toggleMemory"
@forget="forgetMemory"
/>
<div v-for="(step, index) in steps" :key="step.id" class="tree-child" :class="{
'tree-child-last':
!showDoneRow
&& !showWaitStep
&& !showThinkingStep
&& index === steps.length - 1,
}">
<div class="tree-branch" />
<div class="tree-child-content">
<div class="tool-event">
<div
class="action-card"
:class="{ 'has-reference-trigger': step.canOpenReferences }"
:role="step.canOpenReferences ? 'button' : undefined"
:tabindex="step.canOpenReferences ? 0 : undefined"
@click="handleStepClick(step)"
@keydown.enter="handleStepClick(step)"
@keydown.space.prevent="handleStepClick(step)"
>
<div
class="action-header"
:class="{ 'no-results': !step.canOpenReferences }"
>
<div class="action-title">
<ChatTimelineIcon class="action-title-icon" :name="step.iconName" :active="step.pending && !hasAnswer && !session?.is_completed" />
<span class="action-name" :class="{ 'is-running': step.pending }">{{ step.title }}</span>
</div>
</div>
<div v-if="step.summaryHtml" class="search-results-summary-fixed">
<div class="results-summary-text" v-html="step.summaryHtml" />
</div>
</div>
</div>
</div>
</div>
<div
v-if="showWaitStep"
class="tree-child tree-child-last streaming-loading-node rag-model-wait-step"
>
<div class="tree-branch" />
<div class="tree-child-content">
<div class="tool-event">
<div class="action-card" :class="{ 'action-pending': !waitStepStalled }">
<div class="action-header no-results">
<div class="action-title">
<ChatTimelineIcon class="action-title-icon" name="lightbulb" :active="!waitStepStalled" />
<span class="action-name">{{ waitStepText }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div v-if="showThinkingStep" class="tree-child rag-thinking-step"
:class="{ 'tree-child-last': !showDoneRow }">
<div class="tree-branch" />
<div class="tree-child-content">
<div class="tool-event">
<div class="action-card" :class="{ 'action-pending': thinkingPending }">
<div class="action-header" :class="{ 'no-results': !thinkingContent }" @click="toggleThinking">
<div class="action-title">
<ChatTimelineIcon class="action-title-icon" name="lightbulb" :active="thinkingActive" />
<span class="action-name">{{ t('agent.think') }}</span>
</div>
</div>
<div v-if="thinkingContent && thinkingExpanded" class="thinking-detail-content">
{{ thinkingContent }}
</div>
</div>
</div>
</div>
</div>
<div v-if="showDoneRow" class="tree-child agent-step-done tree-child-last">
<div class="tree-branch" />
<div class="tree-child-content">
<div class="tool-event">
<div class="action-card">
<div class="action-header no-results">
<div class="action-title">
<ChatTimelineIcon class="action-title-icon" name="check-circle" />
<span class="action-name">{{ t('common.finish') }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div v-else class="tree-container">
<div class="tool-event">
<div class="action-card tree-root">
<div class="tree-root-toolbar">
<button
type="button"
class="tree-root-expand"
:aria-expanded="showExpandedTimeline"
:aria-label="collapsedStatusText"
@click="toggleExpanded"
>
<span class="tree-root-status">{{ collapsedStatusText }}</span>
<span
v-if="referenceSummaryText"
class="tree-root-reference"
>
{{ referenceSummaryText }}
</span>
<ChatTimelineIcon width="14" height="14"
class="tree-root-expand__icon"
:name="showExpandedTimeline ? 'chevron-down' : 'chevron-right'"
/>
</button>
</div>
</div>
</div>
<div v-if="showExpandedTimeline" class="tree-children tree-children-expanded">
<ChatMemoryStep
v-if="hasMemory"
:memories="memoryItems"
:expanded="memoryExpanded"
:is-last="memoryIsLast"
:forgetting-id="forgettingId"
@toggle="toggleMemory"
@forget="forgetMemory"
/>
<div v-for="(step, index) in steps" :key="step.id" class="tree-child"
:class="{ 'tree-child-last': index === steps.length - 1 && !showDoneRow && !showThinkingStep }">
<div class="tree-branch" />
<div class="tree-child-content">
<div class="tool-event">
<div
class="action-card"
:class="{ 'has-reference-trigger': step.canOpenReferences }"
:role="step.canOpenReferences ? 'button' : undefined"
:tabindex="step.canOpenReferences ? 0 : undefined"
@click="handleStepClick(step)"
@keydown.enter="handleStepClick(step)"
@keydown.space.prevent="handleStepClick(step)"
>
<div
class="action-header"
:class="{ 'no-results': !step.canOpenReferences }"
>
<div class="action-title">
<ChatTimelineIcon class="action-title-icon" :name="step.iconName" :active="step.pending && !hasAnswer && !session?.is_completed" />
<span class="action-name" :class="{ 'is-running': step.pending }">{{ step.title }}</span>
</div>
</div>
<div v-if="step.summaryHtml" class="search-results-summary-fixed">
<div class="results-summary-text" v-html="step.summaryHtml" />
</div>
</div>
</div>
</div>
</div>
<div v-if="showThinkingStep" class="tree-child rag-thinking-step" :class="{ 'tree-child-last': !showDoneRow }">
<div class="tree-branch" />
<div class="tree-child-content">
<div class="tool-event">
<div class="action-card" :class="{ 'action-pending': thinkingPending }">
<div class="action-header" :class="{ 'no-results': !thinkingContent }" @click="toggleThinking">
<div class="action-title">
<ChatTimelineIcon class="action-title-icon" name="lightbulb" :active="thinkingActive" />
<span class="action-name">{{ t('agent.think') }}</span>
</div>
</div>
<div v-if="thinkingContent && thinkingExpanded" class="thinking-detail-content">
{{ thinkingContent }}
</div>
</div>
</div>
</div>
</div>
<div v-if="showDoneRow" class="tree-child agent-step-done tree-child-last">
<div class="tree-branch" />
<div class="tree-child-content">
<div class="tool-event">
<div class="action-card">
<div class="action-header no-results">
<div class="action-title">
<ChatTimelineIcon class="action-title-icon" name="check-circle" />
<span class="action-name">{{ t('common.finish') }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import ChatTimelineIcon from '@/components/ChatTimelineIcon.vue'
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import ChatMemoryStep from './ChatMemoryStep.vue'
import { useChatMemoryRow } from '@/composables/useChatMemoryRow'
import { getAgentToolIconName } from '@/utils/agent-tool-icons'
import {
getKnowledgeSearchSummaryHtml,
getRagPipelineStepTitle,
getRetrievalSearchSource,
} from '@/utils/agent-tool-display'
import { getAttachmentParsingSummaryHtml } from '@/utils/attachmentParsingDisplay'
import { RAG_RETRIEVAL_TOOL_NAMES, RAG_TIMELINE_TOOL_NAMES } from '@/utils/rag-pipeline-history'
import { useChatReferencesDrawer } from '@/composables/useChatReferencesDrawer'
import { buildReferenceSections } from '@/utils/referenceSources'
import {
createRagWaitController,
getRagPipelineWaitKind,
type RagWaitView,
} from '@/utils/rag-pipeline-state'
const props = defineProps<{
session?: {
id?: string | number
agentEventStream?: Array<Record<string, unknown>>
content?: string
knowledge_references?: Array<{ chunk_type?: string; knowledge_id?: string; knowledge_title?: string }>
used_memories?: Array<{ id: string; kind: string; content: string }>
is_completed?: boolean
}
embeddedMode?: boolean
// Set by hosts that already render their own timeline (the agent stream) and
// only need the memory row from here.
memoryOnly?: boolean
}>()
const { t } = useI18n()
const referencesDrawer = useChatReferencesDrawer()
const userExpanded = ref(false)
const thinkingExpanded = ref(true)
const rootElement = ref<HTMLElement | null>(null)
const waitView = ref<RagWaitView>({ kind: 'none', stalled: false })
const waitController = createRagWaitController((view) => {
waitView.value = view
})
// Long-term memory is shown as a timeline row rather than as a card of its
// own: it is one more thing the turn did before answering, and giving it a
// separate visual language would make it read as unrelated to the pipeline.
const {
memoryItems,
hasMemory,
expanded: memoryExpanded,
forgettingId,
toggle: toggleMemory,
forget: forgetMemory,
} = useChatMemoryRow(() => props.session?.used_memories)
const thinkingContent = computed(() => {
const stream = props.session?.agentEventStream
if (!Array.isArray(stream)) return ''
return stream
.filter((event) => event.type === 'thinking')
.map((event) => String(event.content || ''))
.join('')
})
const hasThinking = computed(() => thinkingContent.value.trim().length > 0)
const hasThinkingEvent = computed(() => {
const stream = props.session?.agentEventStream
if (!Array.isArray(stream)) return false
return stream.some((event) => event.type === 'thinking')
})
const hasAnswer = computed(() => {
const sessionContent = props.session?.content
if (typeof sessionContent === 'string' && sessionContent.trim().length > 0) return true
const stream = props.session?.agentEventStream
if (!stream?.length) return false
return stream.some((event) => {
if (event.type !== 'answer' || event.superseded) return false
const content = event.content
return typeof content === 'string' && content.trim().length > 0
})
})
const hasReferences = computed(
() => (props.session?.knowledge_references?.length ?? 0) > 0,
)
const referenceSections = computed(() => buildReferenceSections(props.session?.knowledge_references))
const steps = computed(() => {
const stream = props.session?.agentEventStream
if (!stream?.length) return []
return stream
.filter((event) => {
return (
event.type === 'tool_call' &&
typeof event.tool_name === 'string' &&
RAG_TIMELINE_TOOL_NAMES.has(event.tool_name)
)
})
.map((event) => {
const toolName = String(event.tool_name)
const pending = event.pending === true
const toolData =
event.tool_data && typeof event.tool_data === 'object'
? (event.tool_data as Record<string, unknown>)
: null
const isSearchTool = RAG_RETRIEVAL_TOOL_NAMES.has(toolName)
const isAttachmentTool = toolName === 'attachment_parsing' || toolName === 'image_analysis'
const searchSource = isSearchTool
? getRetrievalSearchSource(event.arguments, toolData)
: undefined
let summaryHtml = ''
if (!pending && isSearchTool && toolData) {
summaryHtml = getKnowledgeSearchSummaryHtml(t, toolData)
} else if (!pending && isAttachmentTool) {
summaryHtml = getAttachmentParsingSummaryHtml(t, event)
}
const canOpenReferences = !pending && isSearchTool && hasReferences.value
return {
id: String(event.tool_call_id || `${toolName}-${event.timestamp || 0}`),
toolName,
pending,
iconName: getAgentToolIconName(toolName, searchSource),
title: getRagPipelineStepTitle(t, {
tool_name: toolName,
pending,
success: event.success as boolean | undefined,
arguments: event.arguments,
tool_data: toolData,
}),
summaryHtml,
canOpenReferences,
}
})
})
const allStepsDone = computed(
() => steps.value.length > 0 && steps.value.every((step) => !step.pending),
)
const hasCompletedRetrievalStep = computed(() => steps.value.some(
(step) => RAG_RETRIEVAL_TOOL_NAMES.has(step.toolName) && !step.pending,
))
const waitKind = computed(() => getRagPipelineWaitKind({
isCompleted: Boolean(props.session?.is_completed),
hasAnswer: hasAnswer.value,
hasThinkingEvent: hasThinkingEvent.value,
stepCount: steps.value.length,
allStepsDone: allStepsDone.value,
hasCompletedRetrievalStep: hasCompletedRetrievalStep.value,
}))
const showWaitStep = computed(() => waitView.value.kind !== 'none')
const waitStepStalled = computed(() => waitView.value.stalled)
const waitStepText = computed(() => {
if (waitView.value.stalled) return t('chat.modelStillResponding')
return waitView.value.kind === 'model'
? t('chat.connectingModelAndGeneratingAnswer')
: t('chat.preparingAnswer')
})
const showCollapsedRoot = computed(
() =>
(hasAnswer.value || Boolean(props.session?.is_completed)) &&
(steps.value.length > 0 || hasThinking.value),
)
const showExpandedTimeline = computed(() => {
if (!showCollapsedRoot.value) return true
return userExpanded.value
})
const showDoneRow = computed(() => {
const turnDone = hasAnswer.value || Boolean(props.session?.is_completed)
if (!turnDone) return false
// A timeline rendered only because memory was used has nothing to report as
// finished; adding a "done" row there would put a step into plain chat that
// never had one.
if (steps.value.length === 0 && !hasThinking.value) return false
if (steps.value.length > 0 && !allStepsDone.value) return false
return true
})
const showPrePipelineWait = computed(() => {
if (hasAnswer.value || props.session?.is_completed || steps.value.length > 0 || hasThinking.value) {
return false
}
// Memory is recalled before the first token, so once it is on screen the
// turn is visibly under way and the placeholder would be redundant.
return !hasMemory.value
})
// Only show the thinking row once the backend actually streams thinking events.
// Do not pre-empt during the model phase — that flashes "思考" even when thinking is disabled.
const showThinkingStep = computed(() => hasThinkingEvent.value)
const thinkingActive = computed(
() => showThinkingStep.value && !hasAnswer.value && !props.session?.is_completed,
)
const thinkingPending = computed(
() =>
showThinkingStep.value &&
!hasThinking.value &&
!hasAnswer.value &&
!props.session?.is_completed,
)
const isThinkingStreaming = computed(
() =>
showThinkingStep.value &&
thinkingExpanded.value &&
!hasAnswer.value &&
!props.session?.is_completed,
)
// Memory alone is enough to render: a plain-chat answer that used memory still
// needs somewhere to say so.
const visible = computed(() => {
if (props.memoryOnly) return hasMemory.value
return (
steps.value.length > 0 || showPrePipelineWait.value || showThinkingStep.value || hasMemory.value
)
})
// The memory row leads the timeline, so it is only the last node when nothing
// else rendered.
const memoryIsLast = computed(
() => steps.value.length === 0 && !showWaitStep.value && !showThinkingStep.value && !showDoneRow.value,
)
const liveStatusText = computed(() => {
if (showPrePipelineWait.value) return t('chat.preparingAnswer')
if (showWaitStep.value) return waitStepText.value
return ''
})
const collapsedStatusText = computed(() => {
if (steps.value.length === 0) {
return hasThinking.value ? t('agentStream.toolStatus.thinkingDone') : ''
}
return t('agentStream.ragPipeline.searchDone')
})
const referenceSummaryText = computed(() => {
const docCount = referenceSections.value.find((section) => section.id === 'documents')?.items.length ?? 0
const webCount = referenceSections.value.find((section) => section.id === 'web')?.items.length ?? 0
if (docCount > 0 && webCount > 0) {
return t('chat.referencesDocAndWebCount', { docCount, webCount })
}
if (docCount > 0) {
return t('chat.referencesDocCount', { count: docCount })
}
if (webCount > 0) {
return t('chat.referencesWebCount', { count: webCount })
}
return ''
})
function toggleReferencesDrawer() {
const refs = props.session?.knowledge_references
if (!referencesDrawer || !refs?.length) return
referencesDrawer.toggle({
references: refs,
highlight: null,
messageId: props.session?.id ? String(props.session.id) : '',
sourceKey: `rag:${props.session?.id || refs.map((item) => item.knowledge_id || item.knowledge_title).join('|')}`,
})
}
function handleStepClick(step: { canOpenReferences?: boolean }) {
if (!step.canOpenReferences) return
toggleReferencesDrawer()
}
function toggleExpanded() {
userExpanded.value = !userExpanded.value
}
function toggleThinking() {
if (!showThinkingStep.value || !thinkingContent.value) return
thinkingExpanded.value = !thinkingExpanded.value
}
function scrollThinkingDetailToBottom() {
nextTick(() => {
if (!rootElement.value) return
rootElement.value.querySelectorAll('.thinking-detail-content').forEach((el) => {
const htmlEl = el as HTMLElement
htmlEl.scrollTop = htmlEl.scrollHeight
})
})
}
watch(thinkingPending, (pending) => {
if (pending) {
thinkingExpanded.value = true
}
})
watch(waitKind, (kind) => waitController.update(kind), { immediate: true })
watch(hasAnswer, (answered) => {
if (answered && hasThinking.value) {
thinkingExpanded.value = false
}
})
watch(thinkingContent, () => {
if (!isThinkingStreaming.value) return
scrollThinkingDetailToBottom()
})
watch(thinkingExpanded, (expanded) => {
if (!expanded || !isThinkingStreaming.value) return
scrollThinkingDetailToBottom()
})
onBeforeUnmount(() => {
waitController.dispose()
})
</script>
<style scoped lang="less">
@import (reference) '@/components/css/chat-timeline-theme.less';
@import '@/components/css/chat-timeline-loading.less';
.rag-pipeline-progress {
.chat-timeline-theme();
margin: 0;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
.tree-container {
margin: 0 0 8px;
position: relative;
}
.tree-root {
margin-bottom: 0;
.tree-root-toolbar {
display: flex;
align-items: center;
justify-content: flex-start;
width: 100%;
min-width: 0;
}
.tree-root-expand {
display: inline-flex;
align-items: center;
gap: 6px;
margin: 0;
padding: 0;
border: 0;
border-radius: var(--app-radius-xs);
background: transparent;
color: var(--td-text-color-secondary);
font-size: var(--app-text-base);
line-height: 22px;
cursor: pointer;
flex: 0 1 auto;
min-width: 0;
max-width: 100%;
&:hover {
background: transparent;
color: var(--td-text-color-primary);
}
}
.tree-root-status,
.tree-root-reference {
flex: 0 1 auto;
min-width: 0;
white-space: nowrap;
}
.tree-root-reference {
display: inline-flex;
align-items: center;
gap: 6px;
&::before {
content: '';
width: 3px;
height: 3px;
border-radius: 50%;
background: currentColor;
opacity: 0.65;
flex-shrink: 0;
}
}
.tree-root-expand__icon {
flex-shrink: 0;
font-size: var(--app-text-base);
color: currentColor;
}
}
.tree-children {
position: relative;
padding-left: 0;
margin-top: 0;
margin-left: 10px;
}
.tree-children-expanded {
margin-top: 14px;
}
.tree-child {
position: relative;
padding-left: 42px;
padding-bottom: 0;
margin-bottom: 14px;
&::before {
content: '';
position: absolute;
left: 9px;
top: 22px;
bottom: -14px;
width: 0;
border-left: 1px solid var(--agent-step-line-color);
}
.tree-branch {
display: none;
}
&.tree-child-last {
margin-bottom: 0;
&::before {
content: none;
}
}
}
.tool-event {
.action-card {
position: relative;
background: transparent;
border: 0;
box-shadow: none;
&.has-reference-trigger {
cursor: pointer;
&:hover {
.action-title-icon,
.action-name,
.results-summary-text {
color: var(--td-text-color-primary);
}
}
}
}
.action-header {
display: flex;
align-items: center;
min-height: 24px;
padding: 0;
cursor: pointer;
user-select: none;
&.no-results {
cursor: default;
}
}
.action-title {
display: flex;
align-items: center;
gap: 12px;
position: relative;
flex: 0 1 auto;
min-width: 0;
.action-show-icon {
flex-shrink: 0;
margin-left: 2px;
}
}
.action-title-icon {
position: absolute;
left: -42px;
top: 3px;
width: 18px;
height: 18px;
flex-shrink: 0;
color: var(--agent-step-icon-color);
}
.action-name {
font-size: var(--agent-step-text-size);
line-height: 1.55;
font-weight: 400;
color: var(--agent-step-color);
word-break: break-word;
max-width: min(820px, 100%);
}
}
.search-results-summary-fixed {
padding: 2px 0 0 0;
.results-summary-text {
font-size: var(--agent-step-summary-size);
font-weight: 400;
color: var(--agent-step-color);
line-height: 1.5;
:deep(strong) {
color: var(--agent-step-color);
font-weight: 500;
}
}
}
.rag-thinking-step {
.thinking-detail-content {
margin-top: 4px;
padding: 0;
font-size: var(--agent-step-summary-size);
font-weight: 400;
color: var(--agent-step-color);
line-height: 1.55;
white-space: pre-wrap;
word-break: break-word;
max-height: 200px;
overflow-y: auto;
}
.action-pending .action-name {
color: var(--agent-step-color);
}
}
@media (max-width: 640px) {
.tree-root {
.tree-root-toolbar {
gap: 8px;
}
.tree-root-expand {
max-width: 100%;
}
}
}
</style>
@@ -0,0 +1,15 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { readFileSync } from 'node:fs'
const desktop = readFileSync(new URL('./SandboxDesktop.vue', import.meta.url), 'utf8')
test('panel open looks up a running sandbox and only provisions on an explicit click', () => {
assert.match(desktop, /connectLookup/)
assert.match(desktop, /onMounted\(\(\) => \{\s*connectLookup\(\)/)
assert.match(desktop, /provision:\s*false/)
assert.match(desktop, /provision:\s*true/)
assert.match(desktop, /status === 'paused'/)
assert.match(desktop, /chat\.sandbox\.desktopPaused/)
assert.match(desktop, /chat\.sandbox\.desktopCreateAndStart/)
})
@@ -0,0 +1,166 @@
<template>
<div class="sandbox-desktop">
<div ref="screenRef" class="sandbox-desktop__screen"
@mousedown="onUserActivity" @keydown="onUserActivity" />
<div v-if="status !== 'connected'" class="sandbox-desktop__overlay">
<div class="sandbox-desktop__overlay-card">
<t-icon v-if="status === 'starting'" name="loading" size="24px"
class="sandbox-desktop__spinner" />
<t-icon v-else-if="status === 'unsupported'" name="error-circle" size="28px" />
<t-icon v-else-if="status === 'busy' || status === 'rebuilt'" name="info-circle" size="28px" />
<t-icon v-else-if="status === 'paused' || (status === 'idle' && hasConnected)" name="time" size="28px" />
<t-icon v-else name="desktop" size="28px" />
<p class="sandbox-desktop__overlay-text">{{ statusText }}</p>
<t-button v-if="actionLabel" size="small"
:theme="status === 'idle' || status === 'needs_provision' || status === 'paused' ? 'primary' : 'default'"
variant="outline" @click.stop="start">
{{ actionLabel }}
</t-button>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, toRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useSandboxDesktop } from '@/composables/useSandboxDesktop'
const props = defineProps<{
sessionId: string
agentId?: string
agentSourceTenantId?: string | number | null
}>()
const { t } = useI18n()
const screenRef = ref<HTMLElement | null>(null)
const desktop = useSandboxDesktop(
toRef(props, 'sessionId'),
toRef(props, 'agentId'),
toRef(props, 'agentSourceTenantId'),
)
const status = desktop.status
// Composable uses 'starting' on first paint (lookup in flight) and 'idle'
// for IDLE_DISCONNECTED. :key="sessionId" remounts this component, so the
// flag resets per session.
const hasConnected = ref(false)
watch(status, (next) => {
if (next === 'connected') hasConnected.value = true
})
const statusText = computed(() => {
switch (status.value) {
case 'starting': return t('chat.sandbox.desktopStarting')
case 'unsupported': return t('chat.sandbox.desktopUnsupported')
case 'busy': return t('chat.sandbox.desktopBusy')
case 'start_failed': return t('chat.sandbox.desktopStartFailed')
case 'rebuilt': return t('chat.sandbox.desktopRebuilt')
case 'needs_provision': return t('chat.sandbox.desktopNeedsProvision')
case 'paused': return t('chat.sandbox.desktopPaused')
case 'unauthorized': return t('chat.sandbox.authRevoked')
case 'disconnected': return t('chat.sandbox.desktopDisconnected')
case 'error': return t('chat.sandbox.desktopDisconnected')
case 'idle':
return hasConnected.value
? t('chat.sandbox.desktopIdleDisconnected')
: t('chat.sandbox.desktopNotStarted')
default: return t('chat.sandbox.desktopNotStarted')
}
})
// unsupported 是配置问题,重试一万次也一样,所以不给按钮。
const actionLabel = computed(() => {
switch (status.value) {
case 'idle':
return hasConnected.value
? t('chat.sandbox.desktopRetry')
: t('chat.sandbox.desktopStart')
case 'paused': return t('chat.sandbox.desktopStart')
case 'needs_provision': return t('chat.sandbox.desktopCreateAndStart')
case 'start_failed':
case 'rebuilt':
case 'busy':
case 'disconnected':
case 'error': return t('chat.sandbox.desktopRetry')
default: return ''
}
})
function start() {
if (!screenRef.value) return
desktop.connect(screenRef.value, { provision: true })
}
function connectLookup() {
if (!screenRef.value) {
void nextTick(() => {
if (screenRef.value) desktop.connect(screenRef.value, { provision: false })
})
return
}
desktop.connect(screenRef.value, { provision: false })
}
onMounted(() => {
connectLookup()
})
// 兜底的活动信号:只有后端 opcode 解析降级时才真正生效,composable 内部已按
// 30 秒 debounce。
function onUserActivity() {
desktop.reportActivity()
}
onBeforeUnmount(() => desktop.dispose())
defineExpose({ start })
</script>
<style scoped lang="less">
.sandbox-desktop {
position: relative;
width: 100%;
height: 100%;
background: #1e1e1e;
overflow: hidden;
}
.sandbox-desktop__screen {
width: 100%;
height: 100%;
}
.sandbox-desktop__overlay {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background: rgba(30, 30, 30, 0.92);
}
.sandbox-desktop__overlay-card {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
max-width: 320px;
padding: 24px;
text-align: center;
color: #d8d8d8;
}
.sandbox-desktop__overlay-text {
margin: 0;
font-size: var(--app-text-md);
line-height: 1.6;
}
.sandbox-desktop__spinner {
animation: wk-spin 1s linear infinite;
}
</style>
@@ -0,0 +1,104 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { execFileSync } from 'node:child_process'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
const terminal = readFileSync(new URL('./SandboxTerminal.vue', import.meta.url), 'utf8')
const theme = readFileSync(new URL('../../../assets/theme/theme.css', import.meta.url), 'utf8')
const promptUrl = new URL('../../../../../docker/sandbox-pty-prompt.sh', import.meta.url)
const prompt = readFileSync(promptUrl, 'utf8')
const promptPath = fileURLToPath(promptUrl)
test('xterm palette keeps prompt green but ls directories blue', () => {
assert.match(theme, /--td-brand-color-4: #07c05f/)
assert.match(terminal, /brightGreen: '#07c05f'/)
assert.match(terminal, /brightBlue: '#729fcf'/)
assert.doesNotMatch(terminal, /brightBlue: '#07c05f'/)
assert.match(terminal, /brightCyan: '#34e2e2'/)
assert.doesNotMatch(terminal, /brightCyan: '#08dd6e'/)
assert.match(prompt, /\\033\[01;32m/)
assert.match(prompt, /\\033\[01;34m/)
assert.doesNotMatch(prompt, /\\033\[01;31m/)
assert.match(prompt, /\]\\W\\\[/)
assert.doesNotMatch(prompt, /\]\\w\\\[/)
})
test('hidden terminal does not resize the live PTY to a zero-size fit', () => {
assert.match(terminal, /function containerHasPtySize/)
assert.match(terminal, /clientWidth >= 20/)
assert.match(terminal, /clientHeight >= 20/)
const start = terminal.indexOf('function applyFit')
const end = terminal.indexOf('function fitAndFocus')
assert.ok(start >= 0 && end > start)
const applyFit = terminal.slice(start, end)
assert.match(applyFit, /containerHasPtySize\(\)/)
assert.match(applyFit, /xterm\.cols < 2 \|\| xterm\.rows < 2/)
})
test('PTY output attaches after the first fit so FitAddon cannot wipe the prompt', () => {
const start = terminal.indexOf('function mountTerminal')
const end = terminal.indexOf('function unmountTerminal')
assert.ok(start >= 0 && end > start)
const mount = terminal.slice(start, end)
const fitAt = mount.indexOf('applyFit()')
const outputAt = mount.indexOf('terminal.onOutput')
assert.ok(fitAt >= 0, 'mountTerminal must fit xterm')
assert.ok(outputAt >= 0, 'mountTerminal must attach PTY output')
assert.ok(
fitAt < outputAt,
'FitAddon.fit() clears the renderer when cols/rows change; flushing the buffered prompt before that fit leaves an empty cursor until the next keystroke',
)
assert.match(terminal, /xterm\.refresh\(0,\s*xterm\.rows\s*-\s*1\)/)
})
test('empty PTY screen is nudged with SIGWINCH, not keystrokes', () => {
assert.match(terminal, /schedulePromptNudge/)
assert.match(terminal, /estimatePtySize/)
assert.match(terminal, /resize\(cols,\s*rows\s*-\s*1\)/)
assert.doesNotMatch(terminal, /sendInput\(PTY_PROMPT_NUDGE\)/)
assert.doesNotMatch(terminal, /sendInput\('\\x0c'\)/)
assert.doesNotMatch(terminal, /sendInput\('\\r'\)/)
})
test('panel open looks up a running sandbox and only provisions on an explicit click', () => {
assert.match(terminal, /connectLookup/)
assert.match(terminal, /onMounted\(\(\) => \{\s*connectLookup\(\)/)
assert.match(terminal, /connect\(\{ provision: false/)
assert.match(terminal, /connect\(\{ provision: true/)
assert.match(terminal, /status === 'paused'/)
assert.match(terminal, /chat\.sandbox\.paused/)
assert.doesNotMatch(terminal, /not_started/)
})
test('a non-reattachable (Docker) terminal never redials silently after ready', () => {
const composable = readFileSync(
new URL('../../../composables/useSandboxTerminal.ts', import.meta.url),
'utf8',
)
assert.match(composable, /reattachable\.value = frame\.reattachable !== false/)
assert.match(composable, /if \(readyReceived && !reattachable\.value\) return\s*scheduleReconnect\(\)/)
assert.match(composable, /code === 'SANDBOX_PAUSED' \|\| code === 'SANDBOX_STOPPED'/)
assert.match(terminal, /chat\.sandbox\.idleDisconnectedNewShell/)
assert.match(terminal, /chat\.sandbox\.disconnectedNewShell/)
assert.match(terminal, /chat\.sandbox\.stopped/)
})
test('interactive bash defines Debian-style ls aliases', () => {
const out = execFileSync('bash', [
'--norc',
'--noprofile',
'-ic',
`. '${promptPath}'; alias ll; alias la; alias l; alias ls; alias grep`,
], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
assert.match(out, /alias ll='ls -alF'/)
assert.match(out, /alias la='ls -A'/)
assert.match(out, /alias l='ls -CF'/)
assert.match(out, /alias ls='ls --color=auto'/)
assert.match(out, /alias grep='grep --color=auto'/)
})
test('interactive prompt script does not export PS1 or PROMPT_COMMAND', () => {
assert.doesNotMatch(prompt, /export PS1/)
assert.doesNotMatch(prompt, /export PROMPT_COMMAND/)
})
@@ -0,0 +1,436 @@
<template>
<div ref="containerRef" class="sandbox-terminal" :class="{ 'is-dark': isDarkTheme }"
@mousedown="focusTerminal">
<div v-if="status !== 'ready'" class="sandbox-terminal__overlay">
<div class="sandbox-terminal__overlay-card">
<t-icon v-if="status === 'connecting'" name="loading" size="24px"
class="sandbox-terminal__spinner" />
<t-icon
v-else-if="status === 'paused' || status === 'needs_provision' || status === 'no_sandbox'"
name="terminal" size="28px" />
<t-icon v-else-if="status === 'unsupported'" name="error-circle" size="28px" />
<t-icon v-else-if="status === 'idle'" name="time" size="28px" />
<t-icon v-else name="cloud" size="28px" />
<p class="sandbox-terminal__overlay-text">{{ statusText }}</p>
<t-button v-if="actionLabel" size="small"
:theme="status === 'needs_provision' ? 'primary' : 'default'" variant="outline"
@click.stop="start">
{{ actionLabel }}
</t-button>
</div>
</div>
<div ref="terminalHost" class="sandbox-terminal__host"></div>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, toRef, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { Terminal } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
import '@xterm/xterm/css/xterm.css';
import { useSandboxTerminal, type SandboxTerminalStatus } from '@/composables/useSandboxTerminal';
import { useTheme } from '@/composables/useTheme';
import { createPtyEchoPredictor } from '@/utils/ptyEchoPredictor';
import {
PTY_PROMPT_NUDGE_DELAY_MS,
xtermBufferLooksEmpty,
} from '@/utils/ptyPromptNudge';
const props = defineProps<{
sessionId: string;
/** 当前会话选中的 agent:首次连接时后端按其配置自动创建沙箱。 */
agentId?: string;
/** 共享智能体的来源空间,与聊天请求的 agent_source_tenant_id 一致。 */
agentSourceTenantId?: string | number | null;
}>();
const { t } = useI18n();
const containerRef = ref<HTMLElement | null>(null);
const terminalHost = ref<HTMLElement | null>(null);
// 主题必须从 useTheme 的共享 ref 派生,不能读 `theme-mode` DOM 属性:DOM 属性
// 不是响应式数据源,那样写出来的 computed 没有任何依赖,求值一次就永久缓存,
// 下面的 watch 永远不会触发,终端配色会一直停在首次挂载时的样子。
const { currentTheme } = useTheme();
const systemPrefersDark = ref(prefersDarkQuery()?.matches === true);
const isDarkTheme = computed(() =>
currentTheme.value === 'system' ? systemPrefersDark.value : currentTheme.value === 'dark',
);
function prefersDarkQuery(): MediaQueryList | null {
if (typeof window === 'undefined' || !window.matchMedia) return null;
return window.matchMedia('(prefers-color-scheme: dark)');
}
// `system` 模式下还要跟随操作系统的实时切换;useTheme 的全局监听只写 DOM
// 属性,不暴露生效后的明暗值,所以这里自己订阅一份。
const prefersDark = prefersDarkQuery();
const onSystemThemeChange = (event: MediaQueryListEvent) => {
systemPrefersDark.value = event.matches;
};
prefersDark?.addEventListener('change', onSystemThemeChange);
// ANSI palette: ls --color uses the usual dircolors mapping (dir=blue,
// exec=green, link=cyan). Only the green slots stay WeKnora brand so
// user@host (01;32) matches the product color; path (01;34) stays blue
// like directories.
function xtermTheme(dark: boolean) {
return dark
? {
background: '#1a1a1a',
foreground: '#e6e6e6',
cursor: '#e6e6e6',
cursorAccent: '#1a1a1a',
selectionBackground: '#3a3a3a',
red: '#c64751',
brightRed: '#de6670',
green: '#06b04d',
brightGreen: '#07c05f',
yellow: '#c4a000',
brightYellow: '#fce94f',
blue: '#3465a4',
brightBlue: '#729fcf',
magenta: '#75507b',
brightMagenta: '#ad7fa8',
cyan: '#06989a',
brightCyan: '#34e2e2',
}
: {
background: '#ffffff',
foreground: '#242424',
cursor: '#242424',
cursorAccent: '#ffffff',
selectionBackground: '#d0d7de',
red: '#e34d59',
brightRed: '#f36d78',
green: '#06b04d',
brightGreen: '#07c05f',
yellow: '#c4a000',
brightYellow: '#c4a000',
blue: '#3465a4',
brightBlue: '#729fcf',
magenta: '#75507b',
brightMagenta: '#ad7fa8',
cyan: '#06989a',
brightCyan: '#34e2e2',
};
}
// toRef 而非 ref(props.x):后者是快照,切换 agent 后重连仍会沿用旧 agent 的
// 沙箱配置去创建沙箱。sessionId 由父组件的 :key 重建兜住,agentId 不会。
const terminal = useSandboxTerminal(
toRef(props, 'sessionId'),
toRef(props, 'agentId'),
toRef(props, 'agentSourceTenantId'),
);
const { status, sandboxMayBeReclaimed, reattachable } = terminal;
const statusText = computed(() => {
switch (status.value as SandboxTerminalStatus) {
case 'paused':
return sandboxMayBeReclaimed.value
? t('chat.sandbox.stopped')
: t('chat.sandbox.paused');
case 'connecting':
return t('chat.sandbox.connecting');
case 'needs_provision':
return t('chat.sandbox.needsProvision');
case 'no_sandbox':
return t('chat.sandbox.noSandbox');
case 'unsupported':
return t('chat.sandbox.unsupported');
case 'exited':
return t('chat.sandbox.sessionEnded');
case 'idle':
return reattachable.value
? t('chat.sandbox.idleDisconnected')
: t('chat.sandbox.idleDisconnectedNewShell');
case 'unauthorized':
return t('chat.sandbox.authRevoked');
default:
return reattachable.value
? t('chat.sandbox.disconnected')
: t('chat.sandbox.disconnectedNewShell');
}
});
// 覆盖层按钮:暂停用「启动终端」,尚未创建用「创建并启动」。点击才允许
// 创建或唤醒;打开面板时的 lookup 不会做这两件事。
const actionLabel = computed(() => {
switch (status.value as SandboxTerminalStatus) {
case 'paused':
return t('chat.sandbox.start');
case 'needs_provision':
return t('chat.sandbox.createAndStart');
case 'error':
case 'exited':
case 'idle':
case 'unauthorized':
// no_sandbox 说的是"智能体没配沙箱后端,无处可建"。用户去配好后应该能
// 直接重试,而不是只能关掉面板再打开——那是个没有任何操作入口的死角。
case 'no_sandbox':
return t('chat.sandbox.retry');
default:
return '';
}
});
// xterm 实例只在 ready 后挂载一次;overlay 覆盖在其上展示状态。
let xterm: Terminal | null = null;
let fitAddon: FitAddon | null = null;
let echo: ReturnType<typeof createPtyEchoPredictor> | null = null;
let resizeObserver: ResizeObserver | null = null;
let resizeDebounce: ReturnType<typeof setTimeout> | null = null;
let promptNudgeTimer: ReturnType<typeof setTimeout> | null = null;
let unmounted = false;
function writeToXterm(chunk: string | Uint8Array) {
xterm?.write(chunk);
}
function focusTerminal() {
if (status.value !== 'ready') return;
xterm?.focus();
}
function mountTerminal() {
if (!terminalHost.value || xterm) return;
xterm = new Terminal({
cursorBlink: true,
cursorStyle: 'bar',
cursorInactiveStyle: 'outline',
fontSize: 13,
fontFamily: "'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace",
theme: xtermTheme(isDarkTheme.value),
scrollback: 5000,
});
echo = createPtyEchoPredictor(writeToXterm);
fitAddon = new FitAddon();
xterm.loadAddon(fitAddon);
xterm.open(terminalHost.value);
xterm.onData((data) => {
echo?.onLocal(data);
terminal.sendInput(data);
});
resizeObserver = new ResizeObserver(() => {
if (resizeDebounce) clearTimeout(resizeDebounce);
resizeDebounce = setTimeout(() => applyFit(), 100);
});
resizeObserver.observe(containerRef.value || terminalHost.value);
// Fit BEFORE flushing buffered PTY bytes. FitAddon.fit() calls
// _renderService.clear() when the default 80x24 becomes the panel size,
// which would wipe a prompt painted a moment earlier and leave only the
// cursor until the next keystroke.
applyFit();
terminal.onOutput((data) => echo?.onRemote(data));
schedulePromptNudge();
void nextTick(() => {
requestAnimationFrame(() => fitAndFocus());
});
}
function unmountTerminal() {
terminal.onOutput(null);
echo = null;
resizeObserver?.disconnect();
resizeObserver = null;
if (resizeDebounce) clearTimeout(resizeDebounce);
resizeDebounce = null;
if (promptNudgeTimer) clearTimeout(promptNudgeTimer);
promptNudgeTimer = null;
xterm?.dispose();
xterm = null;
fitAddon = null;
}
// 覆盖层上唯一会创建或唤醒沙箱的入口。provision: true 表示这是用户的显式
// 确认。组件挂载只做 lookup:运行中的沙箱直接连上,暂停或尚未创建才停在
// 覆盖层等点击。
function start() {
unmountTerminal();
const { cols, rows } = estimatePtySize();
terminal.connect({ provision: true, cols, rows });
}
function connectLookup() {
const { cols, rows } = estimatePtySize();
terminal.connect({ provision: false, cols, rows });
}
onMounted(() => {
connectLookup();
});
watch(isDarkTheme, (dark) => {
if (xterm) xterm.options.theme = xtermTheme(dark);
});
// ready 后挂载 xterm;离开非 ready 状态重置实例(重连 = 新 PTY)。
watch(status, (next, prev) => {
if (next === 'ready' && prev !== 'ready') {
requestAnimationFrame(() => {
// 组件可能在 ready 与下一帧之间就被卸载(关面板 / 切会话)。不校验
// 就会在已销毁的组件上新建 Terminal 并 observe 一个游离节点,那个
// 实例连 watch 都救不回来。
if (unmounted) return;
mountTerminal();
});
} else if (prev === 'ready' && next !== 'ready') {
unmountTerminal();
}
});
// watch(status) 只覆盖"状态离开 ready",覆盖不到组件本身被销毁:关面板走
// SandboxSidePanel 的 v-if、切会话走 :key 重建,两条路径下 status 全程不变,
// watch 不触发。少了这个钩子,每次开关面板都会漏掉一个 xterm 实例
// (渲染器 + 5000 行 scrollback)和一个 ResizeObserver。
onBeforeUnmount(() => {
unmounted = true;
prefersDark?.removeEventListener('change', onSystemThemeChange);
unmountTerminal();
});
function estimatePtySize() {
const el = containerRef.value;
const width = Math.max(0, (el?.clientWidth ?? 0) - 16);
const height = Math.max(0, (el?.clientHeight ?? 0) - 16);
return {
cols: Math.max(20, Math.floor(width / 8) || 80),
rows: Math.max(8, Math.floor(height / 17) || 24),
};
}
function xtermVisibleBufferEmpty(): boolean {
if (!xterm) return true;
const buf = xterm.buffer.active;
const origin = buf.viewportY;
return xtermBufferLooksEmpty(
(row) => buf.getLine(origin + row)?.translateToString(true),
xterm.rows,
);
}
// Pty.Connect does not replay a prompt bash already printed. A same-size
// resize is a no-op; flipping rows by 1 sends SIGWINCH so readline (and
// TUIs) redraw. Do not inject Ctrl-L or Enter: that would go to whatever
// is running in a reattached PTY.
function schedulePromptNudge() {
if (promptNudgeTimer) clearTimeout(promptNudgeTimer);
promptNudgeTimer = setTimeout(() => {
promptNudgeTimer = null;
if (unmounted || !xterm || status.value !== 'ready') return;
if (!xtermVisibleBufferEmpty()) return;
const cols = Math.max(2, xterm.cols);
const rows = Math.max(2, xterm.rows);
terminal.resize(cols, rows - 1);
terminal.resize(cols, rows);
}, PTY_PROMPT_NUDGE_DELAY_MS);
}
// v-show 把终端藏起来时容器是 0×0。FitAddon 仍可能算出 2×1 并送到 PTY,
// 切回终端 tab 时 bash 还停在那组尺寸上,看起来像没连上。尺寸不够就不动。
function containerHasPtySize() {
const el = containerRef.value;
return !!el && el.clientWidth >= 20 && el.clientHeight >= 20;
}
function applyFit() {
if (!xterm || !containerHasPtySize()) return;
try {
fitAddon?.fit();
} catch {
// fit 在容器尺寸为 0 时会抛错,忽略即可。
return;
}
if (xterm.cols < 2 || xterm.rows < 2) return;
terminal.resize(xterm.cols, xterm.rows);
xterm.refresh(0, xterm.rows - 1);
}
function fitAndFocus() {
// v-show 刚打开时 nextTick 里布局可能还没完成,再等两帧再 fit。
requestAnimationFrame(() => {
requestAnimationFrame(() => {
if (unmounted) return;
applyFit();
xterm?.focus();
});
});
}
defineExpose({
focus: fitAndFocus,
});
</script>
<style scoped lang="less">
.sandbox-terminal {
position: relative;
height: 100%;
min-height: 0;
display: flex;
flex-direction: column;
background: var(--td-bg-color-container);
border-radius: var(--app-radius-md);
overflow: hidden;
cursor: text;
}
.sandbox-terminal__host {
flex: 1;
min-height: 0;
padding: 8px;
cursor: text;
:deep(.xterm) {
height: 100%;
cursor: text;
}
:deep(.xterm-viewport) {
overflow-y: auto;
}
:deep(.xterm-helper-textarea) {
// xterm 用隐藏 textarea 接收键盘;必须能获得焦点光标才会闪。
pointer-events: auto;
}
}
.sandbox-terminal__overlay {
position: absolute;
inset: 0;
z-index: 2;
display: flex;
align-items: center;
justify-content: center;
background: var(--td-bg-color-container);
cursor: default;
}
.sandbox-terminal__overlay-card {
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
max-width: 280px;
padding: 20px;
text-align: center;
color: var(--td-text-color-placeholder);
}
.sandbox-terminal__overlay-text {
margin: 0;
font-size: var(--app-text-md);
line-height: 1.6;
white-space: pre-line;
}
.sandbox-terminal__spinner {
animation: wk-spin 0.9s linear infinite;
}
</style>
@@ -0,0 +1,103 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { runInNewContext } from 'node:vm'
import test from 'node:test'
const source = readFileSync(new URL('./ToolApprovalCard.vue', import.meta.url), 'utf8')
const styles = readFileSync(new URL('./agent-interaction-card.less', import.meta.url), 'utf8')
const descriptionCode = source.slice(
source.indexOf('const descriptionParts ='), source.indexOf('const isJsonValid ='),
).replace(/^interface .*$/m, '').replace(/ as \w+\[\]/g, '')
const evaluate = (description, serviceName = 'docs-mcp', delegatedTask = '') => runInNewContext(
descriptionCode + '\n;({ descriptionParts, question, compactDescription, hasLongDescription, argumentSummary })',
{
props: { description, serviceName, delegatedTask },
argsText: { value: '{"period":2,"limit":3}' },
computed: fn => ({ value: fn() }),
isOperation: { value: serviceName === 'WeKnora' },
targetLabel: { value: serviceName + ' › tool' },
t: (key, params) => key.split('.').pop() + ' ' + JSON.stringify(params),
},
)
const parse = (description, serviceName) =>
JSON.parse(JSON.stringify(evaluate(description, serviceName).descriptionParts.value))
test('batch approval retains every title in the separate item list', () => {
const titles = Array.from({ length: 20 }, (_, i) => `Document ${i + 1}`)
const description = ['Delete documents', 'Finance', ...titles.map(title => '- ' + title)].join('\n')
assert.deepEqual(parse(description), { head: 'Delete documents\nFinance', fields: [], items: titles, action: '', target: '' })
})
test('legacy multiline titles remain readable through the scrollable fallback', () => {
const description = 'Delete documents\nFinance\n- First\ncontinued title\n- Last document'
assert.deepEqual(parse(description), { head: description, fields: [], items: [], action: '', target: '' })
assert.match(source, /class="prompt-desc">\{\{ descriptionParts\.head \}\}/)
const fallback = styles.match(/\.prompt-desc \{([\s\S]*?)\n\}/)?.[1]
assert.ok(fallback)
assert.match(fallback, /white-space:\s*pre-line/)
assert.match(fallback, /overflow-y:\s*auto/)
assert.doesNotMatch(fallback, /line-clamp|overflow:\s*hidden/)
})
test('setting lines render as labeled fields and the title stays the headline', () => {
const description = [
'创建知识库',
'助手测试',
'Type: document',
'Embedding model: builtin-embedding',
'Summary model: Qwen',
'Indexes: wiki on',
].join('\n')
assert.deepEqual(parse(description), {
head: '创建知识库\n助手测试',
fields: [
{ label: 'Type', value: 'document' },
{ label: 'Embedding model', value: 'builtin-embedding' },
{ label: 'Summary model', value: 'Qwen' },
{ label: 'Indexes', value: 'wiki on' },
],
items: [],
action: '',
target: '',
})
assert.match(source, /class="prompt-fields"/)
assert.match(styles, /\.prompt-fields \{/)
})
test('a WeKnora operation asks with its summary and target, and counts move out of labels', () => {
const description = [
'创建MCP服务',
'汇率查询 MCP',
'This replaces the stored credentials.',
'URL: https://example.com/mcp',
'Usage instructions (92 characters): 查询汇率',
].join('\n')
const { descriptionParts, question } = evaluate(description, 'WeKnora')
assert.deepEqual(JSON.parse(JSON.stringify(descriptionParts.value)), {
head: 'This replaces the stored credentials.',
fields: [
{ label: 'URL', value: 'https://example.com/mcp' },
{ label: 'Usage instructions', value: '查询汇率', count: '92' },
],
items: [],
action: '创建MCP服务',
target: '汇率查询 MCP',
})
assert.equal(question.value, 'operationQuestion {"action":"创建MCP服务","target":"汇率查询 MCP"}')
assert.match(styles, /\.prompt-field \{\s*display: contents/)
})
test('a warning right after the summary is not mistaken for the target', () => {
const { descriptionParts, question } = evaluate('Update MCP service\nThis drops existing tools.', 'WeKnora')
assert.equal(descriptionParts.value.target, '')
assert.equal(descriptionParts.value.head, 'This drops existing tools.')
assert.equal(question.value, 'operationQuestionNoTarget {"action":"Update MCP service"}')
})
test('delegated approval keeps task separate from description and shows actual arguments', () => {
const result = evaluate('hotlist: Read article rankings.\n\n## Parameters\n- period: days\n\n## Examples\n{}', 'KM', 'hotlist')
assert.equal(result.compactDescription.value, 'Read article rankings.')
assert.equal(result.hasLongDescription.value, true)
assert.match(result.argumentSummary.value, /period=2.*limit=3/)
assert.doesNotMatch(result.descriptionParts.value.head, /^hotlist:/)
})
@@ -0,0 +1,539 @@
<template>
<div v-if="interactive" class="prompt-panel" @click.stop>
<div class="prompt-question">{{ question }}</div>
<div v-if="delegatedTask" class="prompt-task">{{ $t('agentStream.toolApproval.delegatedTask') }} · {{ delegatedTask }}</div>
<div v-if="descriptionParts.head" class="prompt-desc">{{ compactDescription }}</div>
<details v-if="hasLongDescription" class="prompt-tool-description">
<summary>{{ $t('agentStream.toolApproval.toolDescription') }}</summary>
<div class="prompt-desc">{{ descriptionParts.head }}</div>
</details>
<div v-if="delegatedTask && argumentSummary" class="prompt-argument-summary">{{ argumentSummary }}</div>
<dl v-if="descriptionParts.fields.length" class="prompt-fields">
<div v-for="(field, i) in descriptionParts.fields" :key="i" class="prompt-field">
<dt>{{ approvalFieldLabel(field.label) }}</dt>
<dd>
{{ approvalFieldValue(field.label, field.value) }}<span v-if="field.count" class="prompt-field-count">{{
$t('agentStream.toolApproval.characterCount', { count: field.count }) }}</span>
</dd>
</div>
</dl>
<ul v-if="descriptionParts.items.length" class="prompt-desc-items">
<li v-for="(item, i) in descriptionParts.items" :key="i">{{ item }}</li>
</ul>
<div v-if="hasArgs" class="prompt-args">
<button type="button" class="prompt-args-toggle" :aria-expanded="argsExpanded" @click="toggleArgs">
<span>{{ $t('agentStream.toolApproval.argsLabel') }}</span>
<ChatTimelineIcon width="14" height="14" class="args-toggle-icon" :name="argsExpanded ? 'chevron-down' : 'chevron-right'" />
<span v-if="!isJsonValid" class="args-status args-invalid">
<t-icon name="error-circle" />
{{ $t('agentStream.toolApproval.invalidJson') }}
</span>
<span v-else-if="argsDirty" class="args-status args-dirty">
{{ $t('agentStream.toolApproval.argsModified') }}
</span>
</button>
<t-textarea v-if="argsExpanded" v-model="argsText" class="prompt-args-input"
:autosize="{ minRows: 2, maxRows: 10 }" placeholder="{}" />
</div>
<div v-if="grantLapsedText" class="prompt-grant-lapsed">{{ grantLapsedText }}</div>
<t-checkbox v-if="grantScope" v-model="allowInSession" class="prompt-grant">
{{ $t('agentStream.toolApproval.allowInSession') }}
<span class="prompt-grant-scope">{{ grantScope }}</span>
</t-checkbox>
<div class="prompt-footer">
<div class="prompt-footer-meta">
<span v-if="parked" class="action-timer">{{ parkedText }}</span>
<span v-else-if="secondsLeft >= 0" class="action-timer" :class="timerClass">{{ countdownText }}</span>
</div>
<div class="prompt-footer-actions">
<button type="button" class="prompt-btn" :disabled="submitting" @click="submit('reject')">
{{ $t('agentStream.toolApproval.reject') }}
</button>
<button type="button" class="prompt-btn is-primary" :disabled="submitting || !isJsonValid"
@click="submit('approve')">
{{ $t('agentStream.toolApproval.approve') }}<span class="prompt-btn-key" aria-hidden="true">↵</span>
</button>
</div>
</div>
</div>
<div v-else class="action-card interaction-inline approval-inline" :class="{ 'action-pending': open }">
<div class="action-header no-results">
<div class="action-title">
<ChatTimelineIcon class="action-title-icon" :name="headerIcon" :active="open" />
<component :is="hasArgs ? 'button' : 'span'" class="approval-heading"
:type="hasArgs ? 'button' : undefined" :aria-expanded="hasArgs ? argsExpanded : undefined"
@click.stop="hasArgs && toggleArgs()">
<span v-if="delegatedTask" class="approval-task">{{ $t('agentStream.toolApproval.delegatedTask') }} · {{ delegatedTask }}</span>
<span class="action-name">{{ inlineTitle }}</span>
<span class="approval-status" role="status">
{{ awaitingInDock ? $t('agentStream.promptDock.waiting') : statusLine }}
</span>
<ChatTimelineIcon v-if="hasArgs" width="14" height="14" class="args-toggle-icon" :name="argsExpanded ? 'chevron-down' : 'chevron-right'" />
</component>
<button v-if="awaitingInDock" type="button" class="inline-action is-primary" @click.stop="dock?.focus(pendingId)">
{{ $t('agentStream.promptDock.handle') }}
</button>
</div>
</div>
<div v-if="hasArgs && (open || argsExpanded)" class="approval-args">
<button v-if="open" type="button" class="approval-args-toggle" :aria-expanded="argsExpanded" @click.stop="toggleArgs">
<span>{{ $t('agentStream.toolApproval.argsLabel') }}</span>
<span v-if="!argsExpanded && argumentSummary" class="approval-args-summary">{{ argumentSummary }}</span>
<ChatTimelineIcon width="14" height="14" class="args-toggle-icon" :name="argsExpanded ? 'chevron-down' : 'chevron-right'" />
</button>
<div v-else class="approval-args-label">{{ $t('agentStream.toolApproval.argsLabel') }}</div>
<pre v-if="argsExpanded" class="approval-args-content">{{ argsText }}</pre>
</div>
</div>
</template>
<script setup lang="ts">
import ChatTimelineIcon from '@/components/ChatTimelineIcon.vue'
import { ref, computed, inject, watch } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import { resolveToolApproval } from '@/api/mcp-service'
import { resolveEmbedToolApproval } from '@/api/embed'
import { resumeSuspendedRunKey } from '@/utils/suspendedRun'
import { usePromptCountdown } from '@/composables/usePromptCountdown'
import { markPromptSubmitted, promptSubmission, usePromptDock } from '@/composables/usePromptDock'
import { isSubmitKey } from '@/utils/promptKeys'
const props = defineProps<{
pendingId: string
delegatedTask?: string
// dock: the approval form, shown above the composer. inline: the timeline row.
variant?: 'dock' | 'inline'
serviceName: string
mcpToolName: string
description?: string
argsJson?: string
// grantScope, when set, offers to approve calls like this one for the
// rest of the session and says which calls that covers.
grantScope?: string
// grantLapsed is why an earlier "allow" for this call no longer applies.
grantLapsed?: string
timeoutSeconds?: number
requestedAt?: number
resolved?: boolean
approved?: boolean
canceled?: boolean
resolveReason?: string
// suspendable: past hotWaitSeconds the run is suspended rather than failed,
// and the prompt stays answerable until expiresAt.
suspendable?: boolean
hotWaitSeconds?: number
suspended?: boolean
expiresAt?: string
abandoned?: boolean
embeddedMode?: boolean
embedChannelId?: string
embedToken?: string
embedSessionId?: string
embedSessionSig?: string
embedVisitorId?: string
}>()
const useEmbedApproval = () =>
props.embeddedMode
&& props.embedChannelId
&& props.embedToken
&& props.embedSessionId
&& props.embedSessionSig
&& props.embedVisitorId
const { t } = useI18n()
const resumeSuspendedRun = inject(resumeSuspendedRunKey, undefined)
const dock = usePromptDock()
function formatJson(raw: string): string {
try {
return JSON.stringify(JSON.parse(raw), null, 2)
} catch {
return raw
}
}
const initialArgs = formatJson(props.argsJson || '{}')
const argsText = ref(initialArgs)
const argsExpanded = ref(false)
const allowInSession = ref(false)
const GRANT_LAPSE_REASONS = ['changed', 'expired', 'idle']
const grantLapsedText = computed(() => (
props.grantLapsed && GRANT_LAPSE_REASONS.includes(props.grantLapsed)
? t(`agentStream.toolApproval.grantLapsed.${props.grantLapsed}`)
: ''
))
const submitting = ref(false)
const { parked, secondsLeft, timerClass, countdownText, parkedText } = usePromptCountdown(props)
const submission = computed(() => promptSubmission(props.pendingId))
const open = computed(() => !props.resolved && !submission.value)
// A handled approval returns to a compact timeline row, including local submits.
watch([open, () => props.pendingId], () => { argsExpanded.value = false })
// Without a dock (a view that does not provide one) the row stays answerable.
const interactive = computed(() => open.value && (props.variant === 'dock' || !dock))
const awaitingInDock = computed(() => open.value && props.variant !== 'dock' && Boolean(dock?.isDocked(props.pendingId)))
const hasArgs = computed(() => argsText.value.trim().length > 0)
// The service name the backend gives its own operations (run_operation).
const isOperation = computed(() => props.serviceName === 'WeKnora')
// A batch operation ends its description with one "- " line per item it acts
// on; those render as a list so every item stays visible. "Label: value"
// lines render as a definition list. A broken item list stays one block.
interface ApprovalField { label: string, value: string, count?: string }
const descriptionParts = computed(() => {
const raw = (props.description || '').trim()
const prefix = props.delegatedTask ? `${props.delegatedTask}: ` : ''
const text = prefix && raw.startsWith(prefix) ? raw.slice(prefix.length) : raw
const lines = text ? text.split('\n') : []
const start = lines.findIndex((line) => line.startsWith('- '))
const brokenList = start >= 0 && !lines.slice(start).every((line) => line.startsWith('- '))
if (!text || brokenList) {
return { head: text, fields: [], items: [], action: '', target: '' }
}
const body = start < 0 ? lines : lines.slice(0, start)
const items = start < 0 ? [] : lines.slice(start).map((line) => line.slice(2))
const fields = [] as ApprovalField[]
const headLines = [] as string[]
for (const line of body) {
const match = /^([^:\n]{1,48}): (.+)$/.exec(line)
if (!match) {
headLines.push(line)
continue
}
const counted = /^(.+) \((\d+) characters\)$/.exec(match[1])
fields.push(counted
? { label: counted[1], value: match[2], count: counted[2] }
: { label: match[1], value: match[2] })
}
// A WeKnora operation's description opens with its summary, then the label
// of what it acts on; they make the question instead of the raw operation id.
let action = ''
let target = ''
if (isOperation.value && headLines.length) {
action = String(headLines.shift()).trim()
if (headLines.length && !/[.。!!??]$/.test(headLines[0].trim())) target = String(headLines.shift()).trim()
}
return { head: headLines.join('\n').trim(), fields, items, action, target }
})
// Long MCP schemas are reference material. Keep the actual task and arguments
// visible instead of letting parameter documentation occupy the approval dock.
const compactDescription = computed(() => {
const description = descriptionParts.value.head
if (!props.delegatedTask || isOperation.value) return description
return description.split(/\n\s*\n/)[0].slice(0, 180)
})
const hasLongDescription = computed(() => compactDescription.value !== descriptionParts.value.head)
const argumentSummary = computed(() => {
try {
const args = JSON.parse(argsText.value)
if (!args || Array.isArray(args) || typeof args !== 'object') return ''
return Object.entries(args).map(([key, value]) => `${key}=${JSON.stringify(value)}`).join(' · ').slice(0, 240)
} catch { return '' }
})
const question = computed(() => {
const { action, target } = descriptionParts.value
if (!action) return t('agentStream.toolApproval.dockQuestion', { target: targetLabel.value })
return target
? t('agentStream.toolApproval.operationQuestion', { action, target })
: t('agentStream.toolApproval.operationQuestionNoTarget', { action })
})
const isJsonValid = computed(() => {
if (!argsText.value.trim()) return true
try {
JSON.parse(argsText.value)
return true
} catch {
return false
}
})
const approvalDetailKey: Record<string, string> = {
Type: 'type',
'Embedding model': 'embeddingModel',
'Summary model': 'summaryModel',
'Caption model': 'captionModel',
'Speech model': 'speechModel',
Storage: 'storage',
Indexes: 'indexes',
Name: 'name',
Title: 'title',
Status: 'status',
Summary: 'summary',
Model: 'model',
Mode: 'mode',
URL: 'url',
From: 'from',
To: 'to',
Folder: 'folder',
Page: 'page',
Version: 'version',
Documents: 'documents',
'Knowledge bases': 'knowledgeBases',
'MCP services': 'mcpServices',
Skills: 'skills',
'Web search': 'webSearch',
'Multi-turn conversation': 'multiTurn',
Transport: 'transport',
Authentication: 'authentication',
'Usage instructions': 'usageInstructions',
'Display name': 'displayName',
Enabled: 'enabled',
Sandbox: 'sandbox',
Sandboxes: 'sandboxes',
'System prompt': 'systemPrompt',
Content: 'content',
'Knowledge base scope': 'kbScope',
'MCP scope': 'mcpScope',
'Skills scope': 'skillsScope',
}
const approvalValueKey: Record<string, string> = {
document: 'document',
faq: 'faq',
wiki: 'wiki',
on: 'on',
off: 'off',
vector: 'vector',
keyword: 'keyword',
graph: 'graph',
'quick-answer': 'quickAnswer',
'smart-reasoning': 'smartReasoning',
}
function approvalFieldLabel(label: string) {
const key = approvalDetailKey[label]
return key ? t(`agentStream.toolApproval.detail.${key}`) : label
}
function approvalToken(token: string) {
const key = approvalValueKey[token]
return key ? t(`agentStream.toolApproval.value.${key}`) : token
}
function approvalFieldValue(label: string, value: string) {
if (label === 'Indexes') {
const parts = value.split(', ').map((part) => part.split(' ').map(approvalToken).join(' '))
return parts.join(t('agentStream.toolApproval.value.indexSep'))
}
if (label === 'Type' || label === 'Mode' || value === 'on' || value === 'off') {
return approvalToken(value)
}
return value
}
const argsDirty = computed(() => argsText.value.trim() !== initialArgs.trim())
const headerIcon = computed(() => {
if (!props.resolved) return 'secured'
if (props.abandoned || props.canceled) return 'minus-circle'
if (props.approved) return 'check-circle'
return 'close-circle'
})
const targetLabel = computed(() => (
t('agentStream.toolApproval.targetWithTool', {
service: props.serviceName,
tool: props.mcpToolName,
})
))
const inlineTitle = computed(() => {
const { action, target } = descriptionParts.value
return action
? (target ? t('agentStream.toolApproval.operationTarget', { action, target }) : action)
: targetLabel.value
})
const statusLine = computed(() => {
if (!props.resolved) {
return submission.value ? t('agentStream.toolApproval.submitted') : t('agentStream.toolApproval.waitingStatus')
}
if (props.canceled) return t('agentStream.toolApproval.canceledTag')
if (props.abandoned) return t('agentStream.toolApproval.abandonedTag')
if (props.approved) return t('agentStream.toolApproval.approvedTag')
return t('agentStream.toolApproval.rejectedTag')
})
function toggleArgs() {
argsExpanded.value = !argsExpanded.value
}
const allowForSession = (decision: 'approve' | 'reject') => (
decision === 'approve' && Boolean(props.grantScope) && allowInSession.value ? true : undefined
)
const submit = async (decision: 'approve' | 'reject') => {
if (!open.value || submitting.value) return
submitting.value = true
try {
let modified: Record<string, unknown> | undefined
if (decision === 'approve') {
try {
modified = JSON.parse(argsText.value || '{}') as Record<string, unknown>
} catch {
argsExpanded.value = true
MessagePlugin.error(t('agentStream.toolApproval.invalidJson'))
return
}
}
const { resumed } = await (useEmbedApproval()
? resolveEmbedToolApproval(
props.embedChannelId!,
props.embedToken!,
props.embedSessionId!,
props.embedSessionSig!,
props.embedVisitorId!,
props.pendingId,
{
decision,
modified_args: decision === 'approve' ? modified : undefined,
reason: decision === 'reject' ? t('agentStream.toolApproval.userRejected') : undefined,
allow_in_session: allowForSession(decision),
},
)
: resolveToolApproval(props.pendingId, {
decision,
modified_args: decision === 'approve' ? modified : undefined,
reason: decision === 'reject' ? t('agentStream.toolApproval.userRejected') : undefined,
allow_in_session: allowForSession(decision),
}))
markPromptSubmitted(props.pendingId, { approved: decision === 'approve' })
MessagePlugin.success(t('agentStream.toolApproval.submitted'))
if (resumed) resumeSuspendedRun?.(props.pendingId)
} catch (e: any) {
const msg = e?.response?.data?.error?.message || e?.message || t('agentStream.toolApproval.submitFailed')
MessagePlugin.error(msg)
} finally {
submitting.value = false
}
}
/** Enter approves while docked; in the args editor it needs Cmd/Ctrl. */
const handleKey = (e: KeyboardEvent): boolean => {
if (!interactive.value || !isSubmitKey(e)) return false
const inArgs = (e.target as HTMLElement | null)?.tagName === 'TEXTAREA'
if (inArgs && !e.metaKey && !e.ctrlKey) return false
if (!isJsonValid.value) return false
void submit('approve')
return true
}
defineExpose({ handleKey })
</script>
<style scoped lang="less">
@import './agent-interaction-card.less';
.approval-inline {
min-width: 0;
.action-title { column-gap: 8px; row-gap: 4px; }
.action-name { font-size: var(--agent-step-summary-size, 13px); white-space: normal; overflow-wrap: anywhere; flex-shrink: 1; }
}
.approval-status {
padding: 1px 6px;
border-radius: var(--app-radius-sm, 4px);
background: var(--td-bg-color-secondarycontainer);
color: var(--td-text-color-secondary);
font-size: var(--app-text-xs, 12px);
line-height: 1.5;
}
.approval-heading {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
gap: 4px 8px;
min-width: 0;
padding: 0;
border: 0;
background: transparent;
color: inherit;
font: inherit;
text-align: left;
.approval-status, .args-toggle-icon { flex-shrink: 0; }
.args-toggle-icon { color: var(--td-text-color-placeholder); }
}
button.approval-heading {
cursor: pointer;
&:hover { color: var(--td-text-color-primary); }
&:focus-visible { outline: 2px solid var(--td-brand-color); outline-offset: 3px; border-radius: var(--app-radius-xs); }
}
.approval-task {
color: var(--td-text-color-placeholder);
font-size: var(--agent-step-summary-size, 13px);
overflow-wrap: anywhere;
}
.approval-args-label {
padding: 10px 12px 6px;
color: var(--td-text-color-secondary);
font-size: var(--app-text-xs, 12px);
}
.approval-args {
margin-top: 10px;
border-radius: var(--app-radius-md, 8px);
background: var(--td-bg-color-secondarycontainer);
overflow: hidden;
}
.approval-args-toggle {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 10px 12px;
border: 0;
background: transparent;
color: var(--td-text-color-secondary);
font: inherit;
font-size: var(--app-text-xs, 12px);
line-height: 1.5;
text-align: left;
cursor: pointer;
> span:first-child, .args-toggle-icon { flex-shrink: 0; }
.args-toggle-icon { margin-left: auto; }
&:hover { color: var(--td-text-color-primary); }
&:focus-visible { outline: 2px solid var(--td-brand-color); outline-offset: -2px; }
}
.approval-args-summary {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.approval-args-content {
margin: 0;
padding: 0 12px 12px;
max-height: 280px;
overflow: auto;
color: var(--td-text-color-primary);
font-size: var(--app-text-xs, 12px);
line-height: 1.6;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.prompt-task { margin: 6px 0; color: var(--td-text-color-secondary); font-size: var(--app-text-sm); }
.prompt-argument-summary { margin: 8px 0; overflow-wrap: anywhere; font-family: monospace; font-size: var(--app-text-sm); }
.prompt-tool-description { margin-top: 8px; color: var(--td-text-color-secondary); font-size: var(--app-text-sm);
summary { cursor: pointer; }
.prompt-desc { max-height: 180px; overflow-y: auto; white-space: pre-wrap; }
}
</style>
@@ -0,0 +1,308 @@
<template>
<div class="tool-result-renderer">
<!-- Search Results -->
<SearchResults v-if="displayType === 'search_results'" :data="toolData as SearchResultsData"
:arguments="toolArguments" />
<!-- Chunk Detail -->
<ChunkDetail v-else-if="displayType === 'chunk_detail'" :data="toolData as ChunkDetailData" />
<!-- Related Chunks -->
<RelatedChunks v-else-if="displayType === 'related_chunks'" :data="toolData as RelatedChunksData" />
<!-- Knowledge Base List -->
<KnowledgeBaseList v-else-if="displayType === 'knowledge_base_list'" :data="toolData as KnowledgeBaseListData" />
<!-- Document Info -->
<DocumentInfo v-else-if="displayType === 'document_info'" :data="toolData as DocumentInfoData" />
<!-- Graph Query Results -->
<GraphQueryResults v-else-if="displayType === 'graph_query_results'" :data="toolData as GraphQueryResultsData" />
<!-- Thinking Display -->
<ThinkingDisplay v-else-if="displayType === 'thinking'" :data="toolData as ThinkingData" />
<!-- Plan Display -->
<PlanDisplay v-else-if="displayType === 'plan'" :data="toolData as PlanData" />
<!-- Database Query Display -->
<DatabaseQuery v-else-if="displayType === 'database_query'" :data="toolData as DatabaseQueryData" />
<!-- Web Search Results Display -->
<WebSearchResults v-else-if="displayType === 'web_search_results'" :data="toolData as WebSearchResultsData" />
<!-- Web Fetch Results Display -->
<WebFetchResults v-else-if="displayType === 'web_fetch_results'" :data="toolData as WebFetchResultsData" />
<!-- Grep Results Display -->
<GrepResults v-else-if="displayType === 'grep_results'" :data="toolData as GrepResultsData" />
<!-- Knowledge Chunks List -->
<KnowledgeChunksList v-else-if="displayType === 'knowledge_chunks_list'"
:data="toolData as KnowledgeChunksListData" />
<!-- Wiki Edit Results Display -->
<WikiEditResult
v-else-if="displayType === 'wiki_write_page' || displayType === 'wiki_replace_text' || displayType === 'wiki_rename_page' || displayType === 'wiki_delete_page'"
:data="toolData as WikiEditData" />
<ShellExecResult
v-else-if="displayType === 'shell_exec'"
:data="shellExecData"
:output="shellExecOutput"
:arguments="toolArguments"
/>
<div v-else-if="displayType === 'work_wait'" class="work-wait-results">
<p v-if="workNote" class="work-wait-note">{{ workNote }}</p>
<ShellExecResult
v-for="(item, index) in workItems"
:key="item.work_id || index"
:data="shellItemResult(item)"
/>
<div v-if="!workItems.length" class="fallback-output">
<div class="fallback-header">
<span class="fallback-label">{{ $t('chat.rawOutputLabel') }}</span>
</div>
<div class="detail-output-wrapper">
<div class="detail-output">{{ output }}</div>
</div>
</div>
</div>
<SandboxFilesResult
v-else-if="displayType === 'list_sandbox_files'"
:data="toolData as ListSandboxFilesData"
/>
<WriteSandboxFileResult
v-else-if="displayType === 'write_sandbox_file' || displayType === 'edit_sandbox_file'"
:data="toolData as WriteSandboxFileData"
/>
<ReadSkillResult
v-else-if="displayType === 'read_skill'"
:data="toolData as ReadSkillData"
/>
<ImageViewResult
v-else-if="displayType === 'image_view'"
:data="toolData as ImageViewData"
/>
<McpToolResult
v-else-if="displayType === 'mcp_discovery' || displayType === 'mcp_call'"
:discovery="displayType === 'mcp_discovery'" :data="toolData"
:output="output" :arguments="toolArguments" :success="success"
/>
<OperationsResult
v-else-if="displayType === 'find_operations' || displayType === 'run_operation'"
:mode="displayType === 'run_operation' ? 'run' : 'find'"
:output="output" :data="toolData" :success="success"
/>
<WeKnoraDocResult
v-else-if="displayType === 'search_weknora_docs' || displayType === 'read_weknora_doc'"
:mode="displayType === 'read_weknora_doc' ? 'read' : 'search'"
:output="output" :data="toolData" :success="success"
/>
<!-- Unmatched display types still reuse the shell card when the payload is a work list. -->
<div v-else-if="workItems.length" class="work-wait-results">
<p v-if="workNote" class="work-wait-note">{{ workNote }}</p>
<ShellExecResult
v-for="(item, index) in workItems"
:key="item.work_id || index"
:data="shellItemResult(item)"
/>
</div>
<!-- Fallback: Display raw output -->
<div v-else class="fallback-output">
<div class="fallback-header">
<span class="fallback-label">{{ $t('chat.rawOutputLabel') }}</span>
</div>
<div class="detail-output-wrapper">
<div class="detail-output">{{ output }}</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import type {
DisplayType,
SearchResultsData,
ChunkDetailData,
RelatedChunksData,
KnowledgeBaseListData,
DocumentInfoData,
GraphQueryResultsData,
ThinkingData,
PlanData,
DatabaseQueryData,
WebSearchResultsData,
WebFetchResultsData,
GrepResultsData,
KnowledgeChunksListData,
WikiEditData,
ListSandboxFilesData,
WriteSandboxFileData,
ReadSkillData,
ImageViewData
} from '@/types/tool-results';
import SearchResults from './tool-results/SearchResults.vue';
import ChunkDetail from './tool-results/ChunkDetail.vue';
import RelatedChunks from './tool-results/RelatedChunks.vue';
import KnowledgeBaseList from './tool-results/KnowledgeBaseList.vue';
import DocumentInfo from './tool-results/DocumentInfo.vue';
import GraphQueryResults from './tool-results/GraphQueryResults.vue';
import ThinkingDisplay from './tool-results/ThinkingDisplay.vue';
import PlanDisplay from './tool-results/PlanDisplay.vue';
import DatabaseQuery from './tool-results/DatabaseQuery.vue';
import WebSearchResults from './tool-results/WebSearchResults.vue';
import WebFetchResults from './tool-results/WebFetchResults.vue';
import GrepResults from './tool-results/GrepResults.vue';
import KnowledgeChunksList from './tool-results/KnowledgeChunksList.vue';
import WikiEditResult from './tool-results/WikiEditResult.vue';
import ShellExecResult from './tool-results/ShellExecResult.vue';
import SandboxFilesResult from './tool-results/SandboxFilesResult.vue';
import WriteSandboxFileResult from './tool-results/WriteSandboxFileResult.vue';
import ReadSkillResult from './tool-results/ReadSkillResult.vue';
import McpToolResult from './tool-results/McpToolResult.vue';
import ImageViewResult from './tool-results/ImageViewResult.vue';
import OperationsResult from './tool-results/OperationsResult.vue';
import WeKnoraDocResult from './tool-results/WeKnoraDocResult.vue';
interface Props {
success?: boolean;
displayType?: DisplayType;
toolData?: Record<string, any>;
output?: string;
arguments?: Record<string, any>;
}
const props = withDefaults(defineProps<Props>(), { success: undefined });
const displayType = computed(() => props.displayType);
const toolData = computed(() => props.toolData || {});
const output = computed(() => props.output || '');
const toolArguments = computed(() => props.arguments || {});
const shellExecData = computed(() => {
const nested = toolData.value.shell_job
if (nested && typeof nested === 'object' && !Array.isArray(nested)) return nested
return toolData.value
})
const shellExecOutput = computed(() => (
shellExecData.value === toolData.value ? output.value : ''
))
const workItems = computed(() => {
const data = toolData.value
if (Array.isArray(data.items)) return data.items
const nested = data.work
if (nested && typeof nested === 'object' && Array.isArray(nested.items)) return nested.items
return []
})
const workNote = computed(() => {
const data = toolData.value
if (typeof data.note === 'string' && data.note) return data.note
const nested = data.work
if (nested && typeof nested === 'object' && typeof nested.note === 'string') return nested.note
return ''
})
function shellItemResult(item: Record<string, any>) {
const result = item?.result
if (result && typeof result === 'object') return result
return {}
}
</script>
<style lang="less" scoped>
.tool-result-renderer {
margin: 0;
}
.work-wait-results {
display: flex;
flex-direction: column;
gap: 12px;
}
.work-wait-note {
margin: 0;
font-size: var(--app-text-sm);
line-height: 1.4;
color: var(--td-text-color-placeholder);
}
.fallback-output {
margin: 12px 0;
padding: 0;
.fallback-header {
display: flex;
align-items: center;
margin-bottom: 10px;
padding: 0 4px;
.fallback-label {
font-size: var(--app-text-sm);
color: var(--td-text-color-secondary);
font-weight: 500;
line-height: 1.5;
}
}
.detail-output-wrapper {
position: relative;
background: var(--td-bg-color-secondarycontainer);
border: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-sm);
overflow: hidden;
margin: 0;
padding: 0;
.detail-output {
font-family: var(--app-font-family-mono);
font-size: var(--app-text-sm);
color: var(--td-text-color-primary);
padding: 16px;
margin: 0;
white-space: pre-wrap;
word-break: break-word;
line-height: 1.6;
max-height: 400px;
overflow-y: auto;
overflow-x: auto;
background: var(--td-bg-color-container);
display: block;
// 滚动条样式
&::-webkit-scrollbar {
width: 8px;
height: 8px;
}
&::-webkit-scrollbar-track {
background: var(--td-bg-color-secondarycontainer);
border-radius: var(--app-radius-xs);
}
&::-webkit-scrollbar-thumb {
background: var(--td-component-border);
border-radius: var(--app-radius-xs);
&:hover {
background: var(--td-text-color-placeholder);
}
}
}
}
}
</style>
@@ -0,0 +1,544 @@
// Inline interaction rows for OAuth / tool-approval in agent stream.
@import '../../../components/css/chat-timeline-loading.less';
.action-card.interaction-inline {
gap: 0;
}
.action-header {
display: flex;
align-items: center;
min-height: 24px;
padding: 0;
cursor: default;
user-select: none;
}
.action-card {
background: transparent;
border: 0;
box-shadow: none;
display: flex;
flex-direction: column;
}
.interaction-status-summary {
padding: 2px 0 0;
&.is-clickable {
cursor: pointer;
user-select: none;
.results-summary-text {
color: var(--agent-step-color, var(--td-text-color-secondary));
transition: color var(--app-motion-fast) ease;
}
&:hover .results-summary-text {
color: var(--agent-step-color, var(--td-text-color-secondary));
}
}
.results-summary-text {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
font-size: var(--agent-step-summary-size, 13px);
font-weight: 400;
line-height: 1.55;
color: var(--agent-step-color, var(--td-text-color-secondary));
}
.status-label {
flex-shrink: 0;
}
.inline-actions {
display: inline-flex;
align-items: center;
gap: 6px;
flex-shrink: 0;
}
.action-timer {
font-size: var(--app-text-sm);
line-height: 1.55;
font-variant-numeric: tabular-nums;
color: var(--agent-step-color, var(--td-text-color-secondary));
white-space: nowrap;
flex-shrink: 0;
&.timer-warning {
color: var(--td-warning-color);
}
&.timer-critical {
color: var(--td-error-color);
}
}
}
.inline-dot {
color: var(--agent-step-color, var(--td-text-color-secondary));
font-size: var(--app-text-sm);
line-height: 1;
user-select: none;
}
.inline-action {
appearance: none;
border: 0;
background: transparent;
padding: 0;
margin: 0;
font-size: var(--agent-step-summary-size, 13px);
line-height: 1.55;
color: var(--agent-step-color, var(--td-text-color-secondary));
cursor: pointer;
transition: color var(--app-motion-fast) ease;
&:hover:not(:disabled) {
color: var(--agent-step-color, var(--td-text-color-secondary));
}
&:disabled {
opacity: 0.45;
cursor: not-allowed;
}
&.is-primary {
color: var(--td-brand-color);
&:hover:not(:disabled) {
color: var(--td-brand-color-hover);
}
}
}
.action-title {
display: flex;
align-items: center;
gap: 12px;
position: relative;
flex: 1;
min-width: 0;
flex-wrap: wrap;
row-gap: 2px;
.action-title-icon {
position: absolute;
left: -42px;
top: 3px;
flex-shrink: 0;
width: 18px;
height: 18px;
color: var(--agent-step-icon-color, var(--td-text-color-secondary));
}
.action-name {
font-size: var(--agent-step-text-size, 14px);
line-height: 1.55;
font-weight: 400;
color: var(--agent-step-color, var(--td-text-color-secondary));
white-space: nowrap;
flex-shrink: 0;
}
.inline-actions {
display: inline-flex;
align-items: center;
gap: 6px;
flex-shrink: 0;
}
.action-timer {
font-size: var(--app-text-sm);
line-height: 1.55;
font-variant-numeric: tabular-nums;
color: var(--td-text-color-placeholder);
white-space: nowrap;
flex-shrink: 0;
&.timer-warning {
color: var(--td-warning-color);
}
&.timer-critical {
color: var(--td-error-color);
}
}
}
.interaction-args-block {
padding: 4px 0 0;
}
.interaction-args-preview {
padding: 4px 0 0;
font-family: var(--app-font-family-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
font-size: var(--agent-step-summary-size, 13px);
line-height: 1.55;
color: var(--td-text-color-secondary);
white-space: pre-wrap;
word-break: break-word;
max-height: 160px;
overflow: auto;
}
.interaction-args-input {
:deep(.t-textarea__inner) {
font-family: var(--app-font-family-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
font-size: var(--agent-step-summary-size, 13px);
line-height: 1.55;
background: transparent;
border: 0;
box-shadow: none;
color: var(--td-text-color-secondary);
padding: 0;
border-radius: 0;
min-height: 36px;
resize: vertical;
&:focus {
box-shadow: none;
}
}
}
.interaction-args-meta {
display: flex;
align-items: center;
gap: 8px;
font-size: var(--agent-step-summary-size, 13px);
color: var(--td-text-color-placeholder);
.args-status {
display: inline-flex;
align-items: center;
gap: 3px;
font-size: var(--agent-step-summary-size, 13px);
}
}
.args-status {
display: inline-flex;
align-items: center;
gap: 3px;
font-size: var(--agent-step-summary-size, 13px);
&.args-invalid {
color: var(--td-error-color);
}
&.args-dirty {
color: var(--td-warning-color);
}
}
.action-details {
padding: 4px 0 0;
border-top: 0;
background: transparent;
display: flex;
flex-direction: column;
gap: 4px;
}
.args-toggle-row {
gap: 4px;
}
.args-toggle-icon {
flex-shrink: 0;
font-size: var(--app-text-sm);
color: var(--td-text-color-placeholder);
}
// The answerable form of a prompt, rendered in the dock above the composer.
.prompt-panel {
display: flex;
flex-direction: column;
gap: 10px;
}
.prompt-question {
font-size: var(--app-text-base, 14px);
line-height: 1.55;
font-weight: 500;
color: var(--td-text-color-primary);
white-space: pre-wrap;
word-break: break-word;
}
.prompt-desc {
margin-top: -4px;
font-size: var(--agent-step-summary-size, 13px);
line-height: 1.55;
color: var(--td-text-color-secondary);
white-space: pre-line;
word-break: break-word;
max-height: calc(1.55em * 8);
overflow-y: auto;
}
// One grid for all rows, so every value starts at the same column.
.prompt-fields {
display: grid;
grid-template-columns: fit-content(120px) minmax(0, 1fr);
column-gap: 16px;
row-gap: 6px;
align-items: baseline;
margin: 0;
padding: 10px 12px;
border-radius: var(--app-radius-md);
background: var(--td-bg-color-secondarycontainer);
font-size: var(--agent-step-summary-size, 13px);
line-height: 1.55;
max-height: calc(1.55em * 9 + 20px);
overflow-y: auto;
}
.prompt-field {
display: contents;
dt {
margin: 0;
color: var(--td-text-color-placeholder);
}
dd {
margin: 0;
color: var(--td-text-color-primary);
overflow-wrap: anywhere;
}
}
.prompt-field-count {
margin-left: 6px;
color: var(--td-text-color-placeholder);
white-space: nowrap;
}
.prompt-desc-items {
margin: -4px 0 0;
padding-left: 18px;
max-height: calc(1.55em * 8);
overflow-y: auto;
font-size: var(--agent-step-summary-size, 13px);
line-height: 1.55;
color: var(--td-text-color-secondary);
word-break: break-word;
}
.prompt-options {
display: flex;
flex-direction: column;
gap: 2px;
margin: 0 -8px;
}
.prompt-option {
appearance: none;
display: flex;
align-items: center;
gap: 10px;
width: 100%;
padding: 6px 8px;
border: 0;
border-radius: var(--app-radius-md);
background: transparent;
font: inherit;
font-size: var(--app-text-base, 14px);
line-height: 1.5;
text-align: left;
color: var(--td-text-color-primary);
cursor: pointer;
transition: background var(--app-motion-fast) ease;
&:hover:not(:disabled),
&:focus-visible {
background: var(--td-bg-color-container-hover);
outline: none;
}
&:disabled {
opacity: 0.6;
cursor: not-allowed;
}
&.is-selected {
background: var(--td-bg-color-container-hover);
.prompt-option-key {
background: var(--td-brand-color);
color: var(--td-text-color-anti);
}
}
}
.prompt-option-key {
flex-shrink: 0;
display: inline-flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
border-radius: var(--app-radius-sm);
background: var(--td-bg-color-secondarycontainer);
font-size: var(--app-text-sm);
font-weight: 500;
color: var(--td-text-color-secondary);
transition: background var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
}
.prompt-option-label {
flex: 1;
min-width: 0;
word-break: break-word;
}
.prompt-option-check {
flex-shrink: 0;
color: var(--td-brand-color);
}
.prompt-args {
display: flex;
flex-direction: column;
gap: 6px;
}
.prompt-args-toggle {
appearance: none;
display: inline-flex;
align-items: center;
gap: 4px;
align-self: flex-start;
padding: 0;
border: 0;
background: transparent;
font: inherit;
font-size: var(--agent-step-summary-size, 13px);
line-height: 1.55;
color: var(--td-text-color-secondary);
cursor: pointer;
&:hover {
color: var(--td-text-color-primary);
}
.args-status {
margin-left: 6px;
}
}
.prompt-args-input {
:deep(.t-textarea__inner) {
font-family: var(--app-font-family-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
font-size: var(--agent-step-summary-size, 13px);
line-height: 1.55;
background: var(--td-bg-color-secondarycontainer);
border-color: transparent;
border-radius: var(--app-radius-md);
color: var(--td-text-color-secondary);
}
}
.prompt-grant {
align-self: flex-start;
font-size: var(--agent-step-summary-size, 13px);
color: var(--td-text-color-secondary);
}
.prompt-grant-lapsed {
font-size: var(--agent-step-summary-size, 13px);
color: var(--td-warning-color);
}
.prompt-grant-scope {
margin-left: 6px;
color: var(--td-text-color-placeholder);
word-break: break-word;
}
.prompt-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.prompt-footer-meta {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
.action-timer {
font-size: var(--app-text-sm);
line-height: 1.55;
font-variant-numeric: tabular-nums;
color: var(--td-text-color-placeholder);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
&.timer-warning {
color: var(--td-warning-color);
}
&.timer-critical {
color: var(--td-error-color);
}
}
}
.prompt-footer-actions {
display: flex;
align-items: center;
gap: 4px;
flex-shrink: 0;
}
.prompt-btn {
appearance: none;
display: inline-flex;
align-items: center;
height: 28px;
padding: 0 12px;
border: 0;
border-radius: var(--app-radius-md);
background: transparent;
font: inherit;
font-size: var(--agent-step-summary-size, 13px);
color: var(--td-text-color-secondary);
cursor: pointer;
transition: background var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
&:hover:not(:disabled) {
background: var(--td-bg-color-container-hover);
color: var(--td-text-color-primary);
}
&.is-primary {
background: var(--td-brand-color);
color: var(--td-text-color-anti);
&:hover:not(:disabled) {
background: var(--td-brand-color-hover);
color: var(--td-text-color-anti);
}
}
&:disabled {
opacity: 0.45;
cursor: not-allowed;
}
}
.prompt-btn-key {
margin-left: 6px;
font-size: var(--app-text-sm);
opacity: 0.75;
}
@@ -0,0 +1,123 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { readFileSync } from 'node:fs'
import { parse, compileStyle } from '@vue/compiler-sfc'
const botMessage = readFileSync(new URL('./botmsg.vue', import.meta.url), 'utf8')
const agentStream = readFileSync(new URL('./AgentStreamDisplay.vue', import.meta.url), 'utf8')
const chatView = readFileSync(new URL('../index.vue', import.meta.url), 'utf8')
const embedChat = readFileSync(new URL('../../embed/EmbedChatCore.vue', import.meta.url), 'utf8')
const sharedStyles = readFileSync(
new URL('../../../components/css/chat-message-shared.less', import.meta.url),
'utf8',
)
test('user action icon size compiles to a selector matching the button child', () => {
const filename = new URL('./usermsg.vue', import.meta.url)
const { descriptor } = parse(readFileSync(filename, 'utf8'))
const style = descriptor.styles.find(style => style.scoped && !style.lang)
const result = compileStyle({
source: style.content,
filename: filename.pathname,
id: 'data-v-user-message',
scoped: true,
})
assert.deepEqual(result.errors, [])
// A nested :deep() adds an extra descendant scope selector and misses
// the SVG rendered directly inside the action button.
const iconRule = result.rawResult.root.nodes.find(node =>
node.type === 'rule'
&& node.selector === '.user_msg_action[data-v-user-message] .chat-action-icon',
)
assert.ok(iconRule, 'icon sizing must target the direct child without an extra scoped ancestor')
const dimensions = Object.fromEntries(iconRule.nodes
.filter(node => node.type === 'decl' && ['width', 'height'].includes(node.prop))
.map(node => [node.prop, node.value]))
assert.deepEqual(dimensions, { width: '16px', height: '16px' })
})
test('non-agent actions wait for the typewriter buffer to finish', () => {
assert.match(botMessage, /const answerFullyRendered = computed/)
assert.match(botMessage, /typedAnswer\.value\.length >= answerText\.value\.length/)
assert.match(botMessage, /v-if="answerFullyRendered && \(content \|\| session\.content\)"/)
})
test('agent actions reuse the fully-rendered answer state', () => {
assert.match(agentStream, /const answerFullyRendered = computed/)
assert.match(agentStream, /typedAnswer\.value\.length >= activeAnswerMarkdown\.value\.length/)
assert.match(agentStream, /v-if="answerFullyRendered && event\.done/)
})
test('artifact count is a top-right overlay instead of t-badge', () => {
assert.match(botMessage, /class="answer-toolbar__artifact"/)
assert.match(agentStream, /class="answer-toolbar__artifact"/)
assert.match(botMessage, /class="answer-toolbar__artifact-count"/)
assert.match(agentStream, /class="answer-toolbar__artifact-count"/)
assert.match(sharedStyles, /answer-toolbar__artifact-count/)
assert.match(sharedStyles, /position: absolute/)
assert.match(sharedStyles, /td-brand-color/)
assert.match(sharedStyles, /artifact-toolbar-arrive/)
assert.match(botMessage, /is-arrived': artifactArrived/)
assert.match(agentStream, /is-arrived': artifactArrived/)
assert.match(botMessage, /useArtifactArriveMotion/)
assert.match(agentStream, /useArtifactArriveMotion/)
assert.doesNotMatch(botMessage, /<t-badge/)
assert.doesNotMatch(agentStream, /<t-badge/)
})
test('artifact toolbar supports the sandbox panel and session-local drawer', () => {
assert.match(botMessage, /sandboxPanel.open\('artifacts'/)
assert.match(agentStream, /sandboxPanel.open\('artifacts'/)
assert.match(botMessage, /v-if="hasArtifacts && embeddedMode"/)
// Child and standalone viewers also need a drawer. Routing behavior and
// child session identity are covered by AgentStreamDisplay.artifacts.test.
assert.match(agentStream, /v-if="hasArtifacts && useArtifactDrawer/)
assert.match(agentStream, /if \(sandboxPanel && !useArtifactDrawer\.value\)/)
})
test('artifact toolbar uses a folder icon and replaces it while collecting', () => {
assert.match(botMessage, /answer-toolbar__artifact[\s\S]{0,800}name="folder"/)
assert.match(agentStream, /answer-toolbar__artifact[\s\S]{0,800}name="folder"/)
assert.match(botMessage, /class="answer-toolbar__artifact-spinner"/)
assert.match(agentStream, /class="answer-toolbar__artifact-spinner"/)
// 旋转动画统一为 theme.css 里的全局 wk-spin
assert.match(sharedStyles, /answer-toolbar__artifact-spinner[\s\S]{0,400}animation: wk-spin/)
assert.doesNotMatch(botMessage, /answer-toolbar__artifact[\s\S]{0,800}:loading=/)
assert.doesNotMatch(agentStream, /answer-toolbar__artifact[\s\S]{0,800}:loading=/)
})
test('follow-up loading is shown compactly inside both answer toolbars', () => {
assert.match(chatView, /:follow-up-loading="Boolean\(session\.suggestionLoading/)
assert.match(botMessage, /class="answer-toolbar__follow-up-loading"/)
assert.match(agentStream, /class="answer-toolbar__follow-up-loading"/)
assert.match(botMessage, /class="answer-toolbar__follow-up-label"/)
assert.match(botMessage, /transition name="follow-up-toolbar-loading"/)
assert.match(agentStream, /transition name="follow-up-toolbar-loading"/)
assert.match(sharedStyles, /border-left: 1px solid/)
assert.match(sharedStyles, /font-size: (?:12px|var\(--app-text-sm\))/)
assert.match(sharedStyles, /followUpToolbarShimmer 1\.5s linear infinite/)
assert.match(sharedStyles, /background-clip: text/)
assert.match(sharedStyles, /follow-up-toolbar-loading-leave-to/)
})
test('conversation timestamps insert into the message flow instead of each bubble', () => {
assert.match(chatView, /shouldShowConversationTimestamp\(messagesList, index\)/)
assert.match(embedChat, /shouldShowConversationTimestamp\(messagesList, index\)/)
assert.doesNotMatch(chatView, /align="end"/)
assert.doesNotMatch(chatView, /align="start"/)
assert.doesNotMatch(embedChat, /align="end"/)
assert.doesNotMatch(embedChat, /align="start"/)
})
test('follow-up suggestions wait until the answer is fully rendered', () => {
assert.match(
chatView,
/@render-complete-change="\(ready\) => handleAnswerRenderComplete\(session, ready\)"/,
)
assert.match(
chatView,
/<FollowUpSuggestions v-if="!isAutomationSession && session\.answerFullyRendered && !session\.steerForked && !session\.suggestionsDismissed"/,
)
assert.match(botMessage, /emit\('render-complete-change', ready\)/)
assert.match(agentStream, /emit\('render-complete-change', ready\)/)
})
@@ -0,0 +1,677 @@
<template>
<div class="bot_msg" :class="{ 'is-embedded': embeddedMode }">
<div style="display: flex;flex-direction: column; gap:8px">
<!-- 显示@的知识库和文件(非 Agent 模式下显示) -->
<div v-if="!session.isAgentMode && mentionedItems && mentionedItems.length > 0" class="mentioned_items">
<span v-for="item in mentionedItems" :key="item.id" class="mentioned_tag" :class="[
mentionTagClass(item)
]">
<span class="tag_icon">
<t-icon v-if="item.type === 'kb'"
:name="item.kb_type === 'faq' ? 'chat-bubble-help' : 'folder'" />
<t-icon v-else :name="mentionTagIcon(item)" />
</span>
<span class="tag_name">{{ item.name }}</span>
</span>
</div>
<div v-if="session.isRagMode" class="rag-answer-stack">
<RagPipelineProgress :session="session" :embedded-mode="embeddedMode" />
<AgentStreamDisplay v-if="session.isAgentMode" :session="session" :session-id="sessionId"
:user-query="userQuery" :rag-mode="true" :follow-up-loading="followUpLoading"
:embedded-mode="embeddedMode"
:can-fork="canFork"
:can-rewind="canRewind"
@fork="emit('fork', $event)"
@rewind="emit('rewind', $event)"
@render-complete-change="emit('render-complete-change', $event)" />
</div>
<template v-else>
<!-- A plain answer has no timeline to put the memory row on, so
it gets the standalone row. Agent turns render theirs inside
the agent timeline instead, next to the steps it belongs
with. -->
<RagPipelineProgress v-if="!session.isAgentMode && session.used_memories?.length"
:session="session" :embedded-mode="embeddedMode" memory-only />
<docInfo v-if="session.knowledge_references?.length" :session="session"></docInfo>
<AgentStreamDisplay :session="session" :session-id="sessionId" :user-query="userQuery"
v-if="session.isAgentMode" :follow-up-loading="followUpLoading"
:embedded-mode="embeddedMode"
:can-fork="canFork"
:can-rewind="canRewind"
@fork="emit('fork', $event)"
@rewind="emit('rewind', $event)"
@render-complete-change="emit('render-complete-change', $event)" />
</template>
<deepThink :deepSession="session" v-if="session.showThink && !session.isAgentMode"></deepThink>
</div>
<!-- 非 Agent 模式下才显示传统的 markdown 渲染 -->
<div ref="parentMd" v-if="!session.hideContent && !session.isAgentMode">
<!-- 直接渲染完整内容,避免切分导致的问题,样式与 thinking 一致 -->
<!-- 只有当有实际内容时才显示包围框 -->
<div class="content-wrapper" v-if="hasActualContent">
<div class="ai-markdown-template markdown-content" v-stable-html="renderedHTML">
</div>
</div>
<!-- 复制和添加到知识库按钮 - 非 Agent 模式下显示 -->
<div v-if="answerFullyRendered && (content || session.content)" class="answer-toolbar"
:class="{ 'answer-toolbar--persistent': hasArtifacts || artifactsCollecting }">
<t-tooltip v-if="canFork" :content="forkTooltip">
<t-button size="small" variant="outline" shape="round" @click.stop="emitFork">
<ChatActionIcon name="git-branch" />
</t-button>
</t-tooltip>
<t-popconfirm
v-if="canRewind"
:confirm-btn="{ content: t('chat.rewind.confirmButton'), theme: 'danger', size: 'small' }"
:cancel-btn="{ content: t('chat.rewind.cancelButton'), size: 'small' }"
theme="warning"
placement="top"
:show-arrow="false"
overlay-class-name="wk-popover chat-rewind-popconfirm"
@confirm="emitRewind"
>
<template #content>
<div class="chat-rewind-confirm__title">{{ t('chat.rewind.confirmTitle') }}</div>
<div class="chat-rewind-confirm__body">{{ t('chat.rewind.confirmBody') }}</div>
</template>
<t-tooltip :content="rewindTooltip">
<t-button size="small" variant="outline" shape="round" @click.stop>
<ChatActionIcon name="rollback" />
</t-button>
</t-tooltip>
</t-popconfirm>
<t-button v-if="canAskAssistant" size="small" variant="outline" shape="round"
:title="askAssistantTitle" @click.stop="emitAskAssistant">
<ChatActionIcon name="compass" />
</t-button>
<t-button size="small" variant="outline" shape="round" @click.stop="handleCopyAnswer"
:title="$t('agent.copy')">
<ChatActionIcon name="copy" />
</t-button>
<t-button size="small" variant="outline" shape="round" @click.stop="handleAddToKnowledge"
:title="$t('agent.addToKnowledgeBase')">
<ChatActionIcon name="bookmark-add" />
</t-button>
<!-- Skill artifact download: only shown when this reply's
assistant message actually recorded any generated files.
Emptiness is the default: the button stays hidden for
conversational messages that never touched a skill. -->
<span v-if="hasArtifacts || artifactsCollecting" class="answer-toolbar__artifact"
:class="{ 'is-collecting': artifactButtonCollecting, 'is-arrived': artifactArrived }"
@animationend="onArtifactArriveEnd">
<t-button size="small" variant="outline" shape="round"
:disabled="artifactButtonCollecting"
:title="hasArtifacts ? $t('agent.artifactDrawer.buttonTitle') : $t('agent.artifactDrawer.collecting')"
@click.stop="openArtifactDrawer()">
<t-icon v-if="artifactButtonCollecting" name="loading" class="answer-toolbar__artifact-spinner" />
<ChatActionIcon v-else name="folder" />
</t-button>
<span v-if="hasArtifacts" class="answer-toolbar__artifact-count" aria-hidden="true">{{ artifactCount }}</span>
</span>
<!-- Fallback 提示图标 -->
<t-tooltip v-if="session.is_fallback" :content="$t('chat.fallbackHint')" placement="top">
<t-button size="small" variant="outline" shape="round" class="fallback-icon-btn">
<ChatActionIcon name="info-circle" />
</t-button>
</t-tooltip>
<!-- 输出被单次上限截断的提示 -->
<t-tooltip v-if="session.truncated" :content="$t('chat.truncatedHint')" placement="top">
<t-button size="small" variant="outline" shape="round" class="fallback-icon-btn">
<ChatActionIcon name="info-circle" />
</t-button>
</t-tooltip>
<ChatRequestInfoButton v-if="showRequestInfo" :session="session" :session-id="sessionId" />
<transition name="follow-up-toolbar-loading">
<span v-if="followUpLoading" class="answer-toolbar__follow-up-loading" role="status"
aria-live="polite">
<t-icon name="lightbulb" />
<span class="answer-toolbar__follow-up-label">{{ t('chat.followUpQuestionsLoading') }}</span>
</span>
</transition>
</div>
<div v-if="isImgLoading" class="img_loading"><t-loading size="small"></t-loading><span>{{
$t('common.loading') }}</span></div>
</div>
<picturePreview :reviewImg="reviewImg" :reviewUrl="reviewUrl" @closePreImg="closePreImg"></picturePreview>
<Teleport to="body">
<ChatCitationFloat :float="citationFloat" :on-enter="cancelCitationClose"
:on-leave="scheduleCitationClose" />
</Teleport>
<ChatArtifactsDrawer
v-if="hasArtifacts && embeddedMode"
v-model:visible="showArtifactDrawer"
:session-id="sessionId"
:message-id="messageIdForArtifacts"
:artifacts="liveArtifacts"
:preview-index="artifactPreviewIndex"
/>
</div>
</template>
<script setup>
import { onMounted, onBeforeUnmount, watch, computed, ref, reactive, nextTick, onUpdated } from 'vue';
import 'katex/dist/katex.min.css';
import docInfo from './docInfo.vue';
import deepThink from './deepThink.vue';
import AgentStreamDisplay from './AgentStreamDisplay.vue';
import RagPipelineProgress from './RagPipelineProgress.vue';
import ChatActionIcon from '@/components/ChatActionIcon.vue';
import ChatRequestInfoButton from '@/components/ChatRequestInfoButton.vue';
import ChatCitationFloat from '@/components/ChatCitationFloat.vue';
import picturePreview from '@/components/picture-preview.vue';
import ChatArtifactsDrawer from './ChatArtifactsDrawer.vue';
import { isCollectingSkillArtifacts } from '@/utils/skillArtifacts';
import { useArtifactArriveMotion } from '@/composables/useArtifactArriveMotion';
import { useChatSandboxPanel } from '@/composables/useChatSandboxPanel';
import { persistedAssistantId } from '@/utils/steerStreamFork';
import { sanitizeMarkdownHTML, safeMarkdownToHTML, createSafeImage, isValidImageURL, hydrateProtectedFileImages } from '@/utils/security';
import { useProtectedImageRecovery } from '@/composables/useProtectedImageRecovery';
import {
artifactIndexFromEventTarget,
hydrateArtifactImages,
isArtifactRefHref,
renderArtifactReference,
installArtifactLinkRenderer,
} from '@/utils/sandboxArtifactRefs';
import { useI18n } from 'vue-i18n';
import { MessagePlugin } from 'tdesign-vue-next';
import { useUIStore } from '@/stores/ui';
import { useAssistantStore } from '@/stores/assistant';
import {
buildManualMarkdown,
formatManualTitle,
} from '@/utils/chatMessageShared';
import { copyWithToast } from '@/utils/clipboard';
import {
createChatMarkdownRenderer,
renderChatMarkdown,
} from '@/utils/chatMarkdownRenderer';
import {
createMermaidCodeRenderer,
ensureMermaidInitialized,
renderMermaidInContainer,
enhanceMarkdownContainer,
} from '@/utils/mermaidShared';
import { refreshMarkdownEnhancements } from '@/utils/markdownEnhancements';
import { useChatCitationPopover } from '@/composables/useChatCitationPopover';
import { useTypewriter } from '@/composables/useTypewriter';
import { vStableHtml } from '@/directives/stableHtml';
import { SKILL_ICON } from '@/types/mention';
ensureMermaidInitialized();
const mentionTagClass = (item) => {
if (item.type === 'kb') return item.kb_type === 'faq' ? 'faq-tag' : 'kb-tag';
return `${item.type || 'file'}-tag`;
};
const mentionTagIcon = (item) => {
if (item.type === 'tag') return 'tag';
if (item.type === 'mcp') return 'tools';
if (item.type === 'skill') return SKILL_ICON;
return 'file';
};
const emit = defineEmits(['scroll-bottom', 'render-complete-change', 'fork', 'rewind', 'ask-assistant'])
const { t } = useI18n()
const uiStore = useUIStore();
let parentMd = ref()
let reviewUrl = ref('')
let reviewImg = ref(false)
let isImgLoading = ref(false);
const props = defineProps({
// 必填项
content: {
type: String,
required: false
},
session: {
type: Object,
required: false
},
userQuery: {
type: String,
required: false,
default: ''
},
isFirstEnter: {
type: Boolean,
required: false
},
embeddedMode: {
type: Boolean,
default: false
},
sessionId: {
type: String,
default: ''
},
followUpLoading: {
type: Boolean,
default: false
},
canFork: {
type: Boolean,
default: false
},
canRewind: {
type: Boolean,
default: false
},
canAskAssistant: {
type: Boolean,
default: false
}
});
// The popover evaluates sessionId during setup, so it must follow defineProps.
const { float: citationFloat, rebind: rebindCitations, cancelClose: cancelCitationClose, scheduleClose: scheduleCitationClose } = useChatCitationPopover(parentMd, {
getKnowledgeReferences: () => props.session?.knowledge_references,
sessionId: () => props.sessionId,
});
const canFork = computed(() => props.canFork === true && !props.embeddedMode)
const canRewind = computed(() => props.canRewind === true && !props.embeddedMode)
const forkTooltip = '从这条回答继续分叉'
const rewindTooltip = computed(() => t('chat.rewind.tooltip'))
const emitFork = () => {
const messageId = persistedAssistantId(props.session) || props.session?.id
if (messageId) emit('fork', messageId)
}
const emitRewind = () => {
const messageId = persistedAssistantId(props.session) || props.session?.id
if (messageId) emit('rewind', messageId)
}
const assistant = useAssistantStore()
const canAskAssistant = computed(() => props.canAskAssistant === true && !props.embeddedMode)
const askAssistantTitle = computed(() =>
t('assistant.askAboutAnswer', { name: assistant.displayName || t('assistant.title') }))
const emitAskAssistant = () => {
const messageId = persistedAssistantId(props.session) || props.session?.id
if (messageId) emit('ask-assistant', messageId)
}
const showRequestInfo = computed(() => !!(props.session?.request_id || props.session?.id));
// -----------------------------------------------------------------------------
// Skill artifact download (drawer in embedded mode; sandbox panel otherwise)
// -----------------------------------------------------------------------------
// The download button is opt-in per message: the toolbar checks
// `hasArtifacts` and only renders when the assistant message actually
// recorded a file. In the main app this opens the sandbox panel's artifacts
// tab. Embedded chat still uses ChatArtifactsDrawer.
//
// NOTE: this file's <script setup> block is plain JS (no lang="ts"), so we
// stay away from TypeScript-only syntax like `as any[]`.
const showArtifactDrawer = ref(false);
const sandboxPanel = useChatSandboxPanel();
const artifactList = computed(() => {
const raw = props.session && props.session.artifacts;
const list = Array.isArray(raw) ? raw : [];
// Enrich each entry with its position so the download endpoint can
// resolve it. Server responses already include `index` when they come
// via listMessageArtifacts; SSE payloads that land through Message.Artifacts
// omit it. Normalising here keeps ChatArtifactsDrawer index-agnostic.
return list.map((a, i) => ({ index: i, ...a }));
});
// Deleted files stay in artifactList on purpose: the inline renderer needs the
// tombstone to tell "you deleted this" apart from "this handle belongs to some
// other message", and its position is still the download address of the files
// after it. Everything that counts or lists files uses the live view.
const liveArtifacts = computed(() => artifactList.value.filter((a) => !a.deleted_at));
const hasArtifacts = computed(() => liveArtifacts.value.length > 0);
const artifactCount = computed(() => liveArtifacts.value.length);
const { artifactArrived, onArtifactArriveEnd } = useArtifactArriveMotion(artifactCount);
const artifactsCollecting = computed(() => isCollectingSkillArtifacts(props.session));
const artifactButtonCollecting = computed(() => artifactsCollecting.value && !hasArtifacts.value);
const messageIdForArtifacts = computed(() => {
// Steered segments have synthetic row IDs; artifact APIs address the
// persisted assistant. Keep request_id as the in-flight fallback.
return persistedAssistantId(props.session) || String(props.session?.request_id || '');
});
// Set when the drawer is opened by clicking an inline artifact card, so it
// lands directly on that file's preview instead of the list.
const artifactPreviewIndex = ref(null);
function openArtifactDrawer(previewIndex = null) {
if (!hasArtifacts.value) return;
if (sandboxPanel && !props.embeddedMode) {
if (previewIndex == null) {
sandboxPanel.toggleArtifacts(messageIdForArtifacts.value);
} else {
sandboxPanel.open('artifacts', {
messageId: messageIdForArtifacts.value,
previewIndex,
});
}
return;
}
artifactPreviewIndex.value = previewIndex;
showArtifactDrawer.value = true;
}
const artifactRefContext = computed(() => {
const messageId = messageIdForArtifacts.value;
if (!props.sessionId || !messageId) return null;
return { sessionId: props.sessionId, messageId };
});
// Shared replies must authorize files through the persisted message, just as
// AgentStreamDisplay does. The default embed plane still takes precedence.
const protectedFileAccess = computed(() => {
const messageId = persistedAssistantId(props.session);
if (!props.sessionId || !messageId) return undefined;
return { mode: 'message', sessionId: props.sessionId, messageId };
});
const artifactRefLabels = computed(() => ({
previewHint: t('agent.artifactDrawer.inlinePreviewHint'),
missingHint: t('agent.artifactDrawer.inlineMissing'),
deletedHint: t('agent.artifactDrawer.inlineDeleted'),
}));
const preview = (url) => {
nextTick(() => {
reviewUrl.value = url;
reviewImg.value = true
})
}
const closePreImg = () => {
reviewImg.value = false
reviewUrl.value = '';
}
const markdownRenderer = createChatMarkdownRenderer({
codeRenderer: createMermaidCodeRenderer('mermaid-botmsg'),
imageRenderer: ({ href, title, text }) => {
// A sandbox-generated file shares the resource:// form with every other
// protected image, so it is matched against this message's artifacts
// first. Anything that does not belong to this reply falls through to
// the ordinary protected-image path.
const artifactHtml = renderArtifactReference({
href,
alt: text || '',
artifacts: artifactList.value,
labels: artifactRefLabels.value,
context: artifactRefContext.value,
streaming: !props.session?.is_completed,
});
if (artifactHtml !== null) return artifactHtml;
return createSafeImage(href, text || '', title || '');
},
invalidImageHtml: () => `<p>${t('error.invalidImageLink')}</p>`,
isValidImageUrl: (href) => isArtifactRefHref(href) || isValidImageURL(href),
});
installArtifactLinkRenderer(markdownRenderer, () => ({
artifacts: artifactList.value,
labels: artifactRefLabels.value,
context: artifactRefContext.value,
streaming: !props.session?.is_completed,
}));
// 计算属性:将 Markdown 文本转换为 tokens
const mentionedItems = computed(() => {
return props.session?.mentioned_items || [];
});
// Smooth the streamed answer into a steady typewriter cadence (shared with the
// Agent path). Copy/toolbar still read the full content; only display is paced.
const answerText = computed(() => {
const text = props.content || props.session?.content || '';
return typeof text === 'string' ? text : '';
});
const { displayed: typedAnswer } = useTypewriter(
() => answerText.value,
() => Boolean(props.session?.is_completed),
);
// The backend completion event can arrive while the local typewriter still has
// buffered text to reveal. Treat the answer as visually complete only after the
// displayed text has caught up, so actions never appear beside a moving answer.
const answerFullyRendered = computed(() =>
Boolean(props.session?.is_completed) && typedAnswer.value.length >= answerText.value.length
);
useProtectedImageRecovery(() => parentMd.value, () => protectedFileAccess.value,
() => !props.session?.isAgentMode && !props.session?.persistence_error && answerFullyRendered.value);
watch(
answerFullyRendered,
(ready) => {
if (!props.session?.isAgentMode) emit('render-complete-change', ready);
},
{ immediate: true },
);
// 单次渲染整个 Markdown 内容(替代 token-by-token,修复 KaTeX 公式在 streaming 时闪烁消失的问题)
const renderedHTML = computed(() => {
const text = typedAnswer.value;
if (!text || typeof text !== 'string') return '';
return renderChatMarkdown(text, {
renderer: markdownRenderer,
escapeMarkdown: safeMarkdownToHTML,
sanitizeHtml: sanitizeMarkdownHTML,
streaming: !props.session?.is_completed,
knowledgeReferences: props.session?.knowledge_references,
});
});
// 计算属性:判断是否有实际内容(非空且不只是空白)
const hasActualContent = computed(() => {
const text = props.content || props.session?.content || '';
return text && text.trim().length > 0;
});
// 获取实际内容
const getActualContent = () => {
return (props.content || props.session?.content || '').trim();
};
// 复制回答内容
const handleCopyAnswer = async () => {
const content = getActualContent();
if (!content) {
MessagePlugin.warning(t('chat.emptyContentWarning'));
return;
}
await copyWithToast(content, 'common.copySuccess', 'common.copyFailed');
};
// 添加到知识库
const handleAddToKnowledge = () => {
const content = getActualContent();
if (!content) {
MessagePlugin.warning(t('chat.emptyContentWarning'));
return;
}
const question = (props.userQuery || '').trim();
const manualContent = buildManualMarkdown(question, content);
const manualTitle = formatManualTitle(question);
``
uiStore.openManualEditor({
mode: 'create',
title: manualTitle,
content: manualContent,
status: 'draft',
});
MessagePlugin.info(t('chat.editorOpened'));
};
// 处理 markdown-content 中图片的点击事件
const handleMarkdownImageClick = (e) => {
const target = e.target;
const artifactIndex = artifactIndexFromEventTarget(target);
if (artifactIndex !== null) {
e.preventDefault();
e.stopPropagation();
openArtifactDrawer(artifactIndex);
return;
}
if (target && target.tagName === 'IMG') {
const src = target.getAttribute('src');
if (src) {
e.preventDefault();
e.stopPropagation();
preview(src);
}
}
};
watch(renderedHTML, () => {
nextTick(() => {
rebindCitations();
});
});
// 渲染 Mermaid 图表的函数
onUpdated(() => {
nextTick(async () => {
await hydrateProtectedFileImages(parentMd.value, protectedFileAccess.value);
await hydrateArtifactImages(parentMd.value, artifactRefContext.value);
refreshMarkdownEnhancements(parentMd.value);
if (props.session?.is_completed) {
await renderMermaidInContainer(parentMd.value);
}
});
});
onMounted(async () => {
// 为 markdown-content 中的图片添加点击事件
nextTick(async () => {
if (parentMd.value) {
parentMd.value.addEventListener('click', handleMarkdownImageClick, true);
}
rebindCitations();
await hydrateProtectedFileImages(parentMd.value, protectedFileAccess.value);
await hydrateArtifactImages(parentMd.value, artifactRefContext.value);
await enhanceMarkdownContainer(parentMd.value);
});
});
onBeforeUnmount(() => {
if (parentMd.value) {
parentMd.value.removeEventListener('click', handleMarkdownImageClick, true);
}
});
</script>
<style lang="less" scoped>
@import '../../../components/css/chat-markdown.less';
@import '../../../components/css/chat-message-shared.less';
@import '../../../components/css/chat-citations.less';
.bot_msg {
&.is-embedded {
width: 100%;
:deep(.agent-stream-display) {
width: 100%;
}
}
}
.rag-answer-stack {
display: flex;
flex-direction: column;
gap: 0;
}
// 内容包装器 - 与 Agent 模式的 answer 样式一致
.content-wrapper {
padding: 2px 0;
}
.markdown-content {
// Chat Markdown visual styles are centralized in chat-markdown.less.
// Do not add element-level Markdown rules here; update the shared mixin.
.chat-markdown-typography();
.chat-citation-pills();
}
.mentioned_items {
.chat-mentioned-items();
}
.mentioned_tag {
.chat-mentioned-tag();
}
.fallback-icon-btn {
color: var(--td-text-color-disabled) !important;
border-color: var(--td-component-stroke) !important;
&:hover {
color: var(--td-text-color-placeholder) !important;
border-color: var(--td-component-border) !important;
}
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.ai-markdown-img {
max-width: 80%;
max-height: 300px;
width: auto;
height: auto;
border-radius: var(--app-radius-md);
display: block;
cursor: pointer;
object-fit: contain;
margin: 8px 0 8px 16px;
border: 0.5px solid var(--td-component-stroke);
transition: transform var(--app-motion-base) ease;
&:hover {
transform: scale(1.02);
}
}
.bot_msg {
// background: var(--td-bg-color-container);
border-radius: var(--app-radius-xs);
color: var(--td-text-color-primary);
font-size: var(--app-text-xl);
// padding: 10px 12px;
margin-right: auto;
width: 100%;
min-width: 0;
max-width: 100%;
box-sizing: border-box;
}
.botanswer_laoding_gif {
width: 24px;
height: 18px;
margin-left: 16px;
}
.img_loading {
background: var(--td-bg-color-container-hover);
height: 230px;
width: 230px;
color: var(--td-text-color-placeholder);
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
font-size: var(--app-text-sm);
gap: 4px;
margin-left: 16px;
border-radius: var(--app-radius-md);
}
:deep(.t-loading__gradient-conic) {
background: conic-gradient(from 90deg at 50% 50%, #fff 0deg, #676767 360deg) !important;
}
</style>
@@ -0,0 +1,90 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const referenceDrawer = readFileSync(
new URL('../../../components/ChatReferencesDrawer.vue', import.meta.url),
'utf8',
)
const legacyReferences = readFileSync(new URL('./docInfo.vue', import.meta.url), 'utf8')
const agentStream = readFileSync(new URL('./AgentStreamDisplay.vue', import.meta.url), 'utf8')
const chatView = readFileSync(new URL('../index.vue', import.meta.url), 'utf8')
test('reference document links open in a new tab', () => {
assert.match(
referenceDrawer,
/:href="getDocumentHref\(item\)"[\s\S]*?target="_blank"[\s\S]*?rel="noopener noreferrer"/,
)
assert.match(
legacyReferences,
/:href="getDocumentHref\(group\)"[\s\S]*?target="_blank"[\s\S]*?rel="noopener noreferrer"/,
)
})
test('wiki drawer navigation and citation fallbacks open in a new tab', () => {
assert.match(
agentStream,
/:href="wikiGraphHref"[\s\S]*?target="_blank"[\s\S]*?rel="noopener noreferrer"/,
)
assert.match(agentStream, /window\.open\(href, '_blank', 'noopener,noreferrer'\)/)
assert.doesNotMatch(agentStream, /router\.push\(/)
})
test('agent citations recover drawer references from retrieval tool events', () => {
assert.match(
agentStream,
/const getReferencesForDrawer = \([\s\S]*?props\.session\?\.knowledge_references[\s\S]*?props\.session\?\.agentEventStream[\s\S]*?getToolReferenceItems\(event\)/,
)
assert.match(
agentStream,
/const refs = getReferencesForDrawer\(refsOverride\)[\s\S]*?referencesDrawer\.open\(/,
)
assert.match(
agentStream,
/chunk_ids: group\.chunks\.map\(\(chunk\) => chunk\.chunk_id\)\.filter\(Boolean\)/,
)
assert.equal(
agentStream.match(/knowledgeReferences: getReferencesForDrawer\(\)|getReferencesForDrawer\(\),/g)?.length,
3,
)
assert.match(
referenceDrawer,
/watch\(highlight,[\s\S]*?scrollToHighlight\(\)/,
)
assert.equal(
agentStream.match(/documentTitle: title,[\s\S]*?knowledgeBaseId: kbId,/g)?.length,
2,
)
})
test('wiki tool results use the right-side references drawer', () => {
assert.match(
agentStream,
/toolName === 'wiki_search' \|\| toolName === 'wiki_read_page'[\s\S]*?parseWikiToolReferences/,
)
assert.match(
agentStream,
/toolName === 'list_knowledge_chunks' \|\| toolName === 'wiki_read_source_doc'/,
)
assert.match(
agentStream,
/const isReferenceDrawerTool =[\s\S]*?toolName === 'wiki_search'[\s\S]*?toolName === 'wiki_read_page'[\s\S]*?toolName === 'wiki_read_source_doc'/,
)
assert.match(agentStream, /WIKI_EDIT_TOOL_NAMES\.has\(String\(toolName \|\| ''\)\)/)
assert.match(agentStream, /WIKI_ISSUE_TOOL_NAMES\.has\(String\(toolName \|\| ''\)\)/)
})
test('citation highlighting waits for drawer entry and only scrolls its own body', () => {
assert.match(referenceDrawer, /@after-enter="handlePanelAfterEnter"/)
assert.match(referenceDrawer, /if \(!panelEntered\.value\) return/)
assert.match(referenceDrawer, /container\.scrollTo\(\{ top: Math\.max\(0, nextTop\), behavior: 'smooth' \}\)/)
assert.doesNotMatch(referenceDrawer, /el\.scrollIntoView\(/)
})
test('references drawer smoothly shifts the chat area while opening', () => {
assert.match(referenceDrawer, /\.chat-references-panel \{[\s\S]*?position: fixed;/)
assert.match(chatView, /'has-references-panel': referencesDrawerVisible/)
assert.match(chatView, /transition: padding-right (?:0\.3s|var\(--app-motion-slow\)) cubic-bezier\(0\.22, 0\.61, 0\.36, 1\)/)
// The panel widens while showing an original document; 420px is the list width.
assert.match(chatView, /&\.has-references-panel:not\(\.is-embedded\)[\s\S]*?padding-right:\s*var\(--references-panel-width, 420px\)/)
})
@@ -0,0 +1,238 @@
<template>
<div class='deep-think'>
<div class="think-header" @click="toggleFold">
<div class="think-title">
<span v-if="deepSession.thinking" class="thinking-status">
<span class="thinking-indicator">
<span class="indicator-dot"></span>
<span class="indicator-ring"></span>
</span>
<span class="thinking-text">{{ $t('chat.thinking') }}</span>
</span>
<span v-else class="done-status">
<img class="done-icon" src="@/assets/img/Frame3718.svg" :alt="$t('chat.deepThoughtAlt')">
<span class="done-text">{{ $t('chat.deepThoughtCompleted') }}</span>
</span>
</div>
<div class="toggle-icon-wrapper">
<t-icon :name="isFold ? 'chevron-down' : 'chevron-up'" class="toggle-icon" />
</div>
</div>
<div class="think-content" v-show="!isFold || deepSession.thinking">
<div ref="contentInnerRef" class="content-inner">{{ deepSession.thinkContent }}</div>
</div>
</div>
</template>
<script setup>
import { watch, ref, onMounted, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
const isFold = ref(false)
const contentInnerRef = ref(null)
const { t } = useI18n()
const props = defineProps({
// 必填项
deepSession: {
type: Object,
required: false
}
});
// 初始化时检查:如果 thinking 已完成(从历史记录加载),默认折叠
onMounted(() => {
if (props.deepSession?.thinking === false) {
isFold.value = true;
}
});
// 监听 thinking 状态变化,自动折叠
watch(
() => props.deepSession?.thinking,
(newVal, oldVal) => {
// 当 thinking 从 true 变为 false 时,自动折叠 thinking 内容
// 只在流式输出场景下触发(oldVal 为 true)
if (oldVal === true && newVal === false) {
isFold.value = true;
}
}
);
// 监听内容变化,自动滚动到底部
watch(
() => props.deepSession?.thinkContent,
() => {
// 只在 thinking 进行中时滚动
if (props.deepSession?.thinking) {
nextTick(() => {
if (contentInnerRef.value) {
contentInnerRef.value.scrollTop = contentInnerRef.value.scrollHeight;
}
});
}
}
);
const toggleFold = () => {
// 只有 thinking 完成后才能折叠/展开
if (!props.deepSession?.thinking) {
isFold.value = !isFold.value;
}
}
</script>
<style lang="less" scoped>
.deep-think {
display: flex;
flex-direction: column;
font-size: var(--app-text-sm);
width: 100%;
border-radius: var(--app-radius-md);
background-color: var(--td-bg-color-container);
border: .5px solid var(--td-component-stroke);
box-shadow: 0 2px 4px color-mix(in srgb, var(--td-brand-color) 8%, transparent);
overflow: hidden;
box-sizing: border-box;
transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
margin: -8px 0px 10px 0px;
.think-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 6px 14px;
color: var(--td-text-color-primary);
font-weight: 500;
cursor: pointer;
user-select: none;
&:hover {
background-color: color-mix(in srgb, var(--td-brand-color) 4%, transparent);
}
.think-title {
display: flex;
align-items: center;
}
.thinking-status {
display: flex;
align-items: center;
.thinking-indicator {
position: relative;
width: 16px;
height: 16px;
margin-right: 8px;
display: flex;
align-items: center;
justify-content: center;
.indicator-dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--td-brand-color);
animation: pulse-dot 1.8s ease-in-out infinite;
}
.indicator-ring {
position: absolute;
inset: 0;
border-radius: 50%;
border: 1.5px solid var(--td-brand-color);
opacity: 0;
animation: pulse-ring 1.8s ease-out infinite;
}
}
.thinking-text {
font-size: var(--app-text-sm);
color: var(--td-text-color-primary);
white-space: nowrap;
}
}
.done-status {
display: flex;
align-items: center;
.done-icon {
width: 16px;
height: 16px;
margin-right: 8px;
}
.done-text {
font-size: var(--app-text-sm);
color: var(--td-text-color-primary);
white-space: nowrap;
}
}
.toggle-icon-wrapper {
font-size: var(--app-text-base);
padding: 0 2px 1px 2px;
color: var(--td-brand-color);
.toggle-icon {
transition: transform var(--app-motion-base);
}
}
}
.think-content {
border-top: 1px solid var(--td-bg-color-secondarycontainer);
.content-inner {
padding: 8px 14px;
font-size: var(--app-text-sm);
line-height: 1.6;
color: var(--td-text-color-secondary);
max-height: 200px;
overflow-y: auto;
word-break: break-word;
white-space: pre-wrap;
&::-webkit-scrollbar {
width: 4px;
}
&::-webkit-scrollbar-thumb {
background: rgba(0, 0, 0, 0.1);
border-radius: 2px;
}
}
}
}
@keyframes pulse-dot {
0%, 100% {
transform: scale(0.85);
opacity: 0.6;
}
50% {
transform: scale(1.1);
opacity: 1;
}
}
@keyframes pulse-ring {
0% {
transform: scale(0.5);
opacity: 0.6;
}
100% {
transform: scale(1.2);
opacity: 0;
}
}
html[theme-mode="dark"] {
.deep-think {
.think-content .content-inner {
&::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.15);
}
}
}
}
</style>
@@ -0,0 +1,18 @@
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, 'docInfo.vue'), 'utf8')
test('timeline references neutralize brand colors via local css variables', () => {
assert.match(source, /&\.refer-timeline \{[\s\S]*--td-brand-color:\s*var\(--td-text-color-placeholder\)/)
assert.match(source, /\.doc-chunk-item \.doc-chunk-text:hover/)
})
test('doc header uses right/down chevron on the outer title only', () => {
assert.match(source, /showReferBox \? 'chevron-down' : 'chevron-right'/)
assert.doesNotMatch(source, /class="doc-group-arrow"/)
})
@@ -0,0 +1,508 @@
<template>
<div class="refer" :class="{ 'refer-timeline': timelineMode }"
v-if="session.knowledge_references && session.knowledge_references.length">
<div class="refer_header" v-if="!contentOnly" @click="referBoxSwitch">
<div class="refer_title">
<t-icon v-if="!timelineMode" name="file" class="refer-title-icon" />
<span>{{ headerText }}</span>
<div class="refer_show_icon">
<t-icon :name="showReferBox ? 'chevron-down' : 'chevron-right'" />
</div>
</div>
</div>
<div class="refer_box" v-show="contentOnly || showReferBox">
<!-- Web search references (ungrouped) -->
<div v-for="(item, index) in webSearchRefs" :key="'web-' + index">
<a :href="getWebSearchUrl(item)" target="_blank" rel="noopener noreferrer" class="doc doc-web"
@click.stop>
{{ webSearchRefs.length < 2 ? getWebSearchDisplayText(item) : `${index + 1}.
${getWebSearchDisplayText(item)}` }} </a>
</div>
<!-- Knowledge references grouped by document -->
<div v-for="(group, gIdx) in groupedKnowledgeRefs" :key="'grp-' + gIdx" class="doc-group">
<div class="doc-group-header" @click="toggleGroup(group.key)">
<div class="doc-group-left">
<t-icon name="file" size="14px" class="doc-group-icon" />
<span class="doc-group-title" :title="group.title">{{ group.title }}</span>
<span class="doc-group-count">{{ $t('chat.referenceChunkCount', { count: group.chunks.length })
}}</span>
</div>
<div class="doc-group-actions" v-if="!embeddedMode && group.knowledgeBaseId" @click.stop>
<t-tooltip :content="$t('chat.navigateToDocument')">
<a
class="doc-group-navigate"
:href="getDocumentHref(group)"
target="_blank"
rel="noopener noreferrer"
>
<t-icon name="jump" size="14px" />
</a>
</t-tooltip>
</div>
</div>
<div class="doc-group-chunks" v-show="expandedGroups[group.key]">
<div v-for="(chunk, cIdx) in group.chunks" :key="'chunk-' + cIdx" class="doc-chunk-item">
<t-popup overlayClassName="refer-to-layer" placement="bottom-left" width="400"
:showArrow="false" trigger="click">
<template #content>
<ContentPopup :content="safeProcessContent(chunk.content)" :is-html="true" />
</template>
<span class="doc-chunk-text">
<span class="doc-chunk-index">{{ $t('chat.chunkLabel', { index: cIdx + 1 }) }}</span>
{{ truncateContent(chunk.content, 80) }}
</span>
</t-popup>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { computed, ref, reactive } from "vue";
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { sanitizeHTML } from '@/utils/security';
import ContentPopup from './tool-results/ContentPopup.vue';
import { useChatReferencesDrawer } from '@/composables/useChatReferencesDrawer';
const router = useRouter();
const { t } = useI18n();
const referencesDrawer = useChatReferencesDrawer();
const props = defineProps({
content: {
type: String,
required: false
},
session: {
type: Object,
required: false
},
embeddedMode: {
type: Boolean,
default: false
},
timelineMode: {
type: Boolean,
default: false
},
contentOnly: {
type: Boolean,
default: false
}
});
const showReferBox = ref(false);
const expandedGroups = reactive({});
const referBoxSwitch = () => {
const refs = props.session?.knowledge_references;
if (referencesDrawer && refs?.length) {
referencesDrawer.open({ references: refs });
return;
}
showReferBox.value = !showReferBox.value;
};
const toggleGroup = (key) => {
expandedGroups[key] = !expandedGroups[key];
};
const webSearchRefs = computed(() => {
if (!props.session?.knowledge_references) return [];
return props.session.knowledge_references.filter(item => item.chunk_type === 'web_search');
});
const knowledgeRefs = computed(() => {
if (!props.session?.knowledge_references) return [];
return props.session.knowledge_references.filter(item => item.chunk_type !== 'web_search');
});
const groupedKnowledgeRefs = computed(() => {
const refs = knowledgeRefs.value;
if (!refs.length) return [];
const groupMap = new Map();
for (const item of refs) {
const key = item.knowledge_id || item.knowledge_title || item.id;
if (!groupMap.has(key)) {
groupMap.set(key, {
key,
title: item.knowledge_title || item.knowledge_filename || key,
knowledgeId: item.knowledge_id,
knowledgeBaseId: item.knowledge_base_id,
chunks: [],
});
}
groupMap.get(key).chunks.push(item);
}
return Array.from(groupMap.values());
});
const headerText = computed(() => {
const total = props.session?.knowledge_references?.length ?? 0;
const docCount = groupedKnowledgeRefs.value.length;
const webCount = webSearchRefs.value.length;
if (docCount > 0 && webCount > 0) {
return t('chat.referencesDocAndWebCount', { docCount, webCount });
}
if (docCount > 0) {
return t('chat.referencesDocCount', { count: docCount });
}
if (webCount > 0) {
return t('chat.referencesWebCount', { count: webCount });
}
return t('chat.referencesTitle', { count: total });
});
const safeProcessContent = (content) => {
if (!content) return '';
const sanitized = sanitizeHTML(content);
return sanitized.replace(/\n/g, '<br/>');
};
const truncateContent = (content, maxLen) => {
if (!content) return '';
const text = content.replace(/\n/g, ' ').trim();
if (text.length <= maxLen) return text;
return text.slice(0, maxLen) + '...';
};
const getDocumentHref = (group) => {
if (!group.knowledgeBaseId) return '';
const query = {};
if (group.knowledgeId) {
query.knowledge_id = group.knowledgeId;
}
return router.resolve({
path: `/platform/knowledge-bases/${group.knowledgeBaseId}`,
query
}).href;
};
const getWebSearchUrl = (item) => {
if (item.metadata?.url) {
return item.metadata.url;
}
if (item.id && (item.id.startsWith('http://') || item.id.startsWith('https://'))) {
return item.id;
}
return '#';
};
const getWebSearchDisplayText = (item) => {
if (item.knowledge_title) {
return item.knowledge_title;
}
if (item.metadata?.title) {
return item.metadata.title;
}
const url = getWebSearchUrl(item);
if (url && url !== '#') {
try {
const urlObj = new URL(url);
return urlObj.hostname;
} catch {
return url;
}
}
return 'Web Search Result';
};
</script>
<style lang="less" scoped>
.refer {
--refer-brand-4: color-mix(in srgb, var(--td-brand-color) 4%, transparent);
--refer-brand-8: color-mix(in srgb, var(--td-brand-color) 8%, transparent);
--refer-brand-12: color-mix(in srgb, var(--td-brand-color) 12%, transparent);
display: flex;
flex-direction: column;
font-size: var(--app-text-sm);
width: 100%;
border-radius: var(--app-radius-md);
background-color: var(--td-bg-color-container);
border: .5px solid var(--td-component-stroke);
box-shadow: 0 2px 4px var(--refer-brand-8);
box-sizing: border-box;
overflow: hidden;
box-sizing: border-box;
transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
margin-bottom: 8px;
&.refer-timeline {
--td-brand-color: var(--td-text-color-placeholder);
--embed-primary: var(--td-text-color-placeholder);
--refer-brand-4: color-mix(in srgb, var(--td-text-color-primary) 4%, transparent);
--refer-brand-8: color-mix(in srgb, var(--td-text-color-primary) 6%, transparent);
--refer-brand-12: color-mix(in srgb, var(--td-text-color-primary) 8%, transparent);
width: 100%;
border-radius: 0;
background-color: transparent;
border: 0;
box-shadow: none;
margin-bottom: 0;
font-size: var(--app-text-md);
.refer_header {
padding: 0;
font-weight: 400;
color: var(--td-text-color-secondary);
.refer_title span {
font-size: var(--app-text-base);
white-space: normal;
}
}
.refer_header:hover {
background-color: transparent;
}
.refer_show_icon {
color: var(--td-text-color-placeholder);
}
.refer_box {
padding: 2px 0 0 0;
border-top: 0;
}
.doc-group {
margin-top: 2px;
}
.doc-group-header {
padding: 2px 0;
}
.doc-group-title {
color: var(--td-text-color-secondary);
font-weight: 400;
font-size: var(--app-text-md);
max-width: min(520px, 100%);
}
.doc-group-count,
.doc-chunk-text,
.doc-chunk-index {
font-size: var(--app-text-sm);
}
.doc-group-icon {
color: var(--td-text-color-placeholder);
}
.doc-group-navigate {
color: var(--td-text-color-placeholder);
}
.doc {
color: var(--td-text-color-secondary);
border-bottom-color: color-mix(in srgb, var(--td-text-color-secondary) 30%, transparent);
}
.doc-chunk-item .doc-chunk-text:hover {
background-color: var(--refer-brand-4);
color: var(--td-text-color-secondary);
}
}
.refer_header {
display: flex;
align-items: center;
padding: 6px 14px;
color: var(--td-text-color-primary);
font-weight: 500;
.refer_title {
display: inline-flex;
align-items: center;
gap: 4px;
min-width: 0;
span {
white-space: nowrap;
font-size: var(--app-text-sm);
}
}
.refer_show_icon {
font-size: var(--app-text-base);
padding: 0 2px 1px 2px;
color: var(--td-brand-color);
flex-shrink: 0;
}
}
.refer_header:hover {
background-color: var(--refer-brand-4);
cursor: pointer;
}
.refer_box {
padding: 4px 14px 8px 14px;
flex-direction: column;
border-top: 1px solid var(--td-bg-color-secondarycontainer);
}
}
.refer-title-icon {
width: 16px;
height: 16px;
margin-right: 8px;
flex-shrink: 0;
color: var(--embed-primary, var(--td-brand-color));
}
.doc {
text-decoration: none;
color: var(--td-brand-color);
cursor: pointer;
display: inline-block;
white-space: nowrap;
max-width: calc(100% - 24px);
overflow: hidden;
text-overflow: ellipsis;
line-height: 20px;
padding: 2px 0;
transition: all var(--app-motion-base) ease;
border-bottom: 1px dashed var(--td-brand-color);
&:hover {
background-color: var(--refer-brand-8);
border-radius: 3px;
padding-right: 4px;
}
&.doc-web {
white-space: normal;
word-break: break-all;
}
}
.doc-group {
margin-top: 4px;
.doc-group-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 4px 4px;
border-radius: var(--app-radius-xs);
cursor: pointer;
transition: background-color var(--app-motion-fast) ease;
&:hover {
background-color: var(--refer-brand-4);
}
.doc-group-left {
display: flex;
align-items: center;
min-width: 0;
flex: 1;
}
.doc-group-arrow {
color: var(--td-text-color-placeholder);
flex-shrink: 0;
margin-left: 4px;
}
.doc-group-icon {
color: var(--td-brand-color);
flex-shrink: 0;
margin-right: 6px;
}
.doc-group-title {
color: var(--td-text-color-primary);
font-weight: 500;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 200px;
}
.doc-group-count {
color: var(--td-text-color-placeholder);
font-size: var(--app-text-xs);
margin-left: 6px;
white-space: nowrap;
flex-shrink: 0;
}
.doc-group-actions {
flex-shrink: 0;
margin-left: 8px;
}
.doc-group-navigate {
display: inline-flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
border-radius: var(--app-radius-xs);
color: var(--td-brand-color);
cursor: pointer;
text-decoration: none;
transition: all var(--app-motion-fast) ease;
&:hover {
background-color: var(--refer-brand-12);
}
}
}
.doc-group-chunks {
padding-left: 22px;
}
}
.doc-chunk-item {
.doc-chunk-text {
display: block;
color: var(--td-text-color-secondary);
font-size: var(--app-text-sm);
line-height: 18px;
padding: 3px 6px;
border-radius: var(--app-radius-xs);
cursor: pointer;
transition: background-color var(--app-motion-fast) ease;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
&:hover {
background-color: var(--refer-brand-4);
color: var(--td-brand-color);
}
.doc-chunk-index {
color: var(--td-text-color-placeholder);
font-size: var(--app-text-xs);
margin-right: 4px;
}
}
}
</style>
<style>
.refer-to-layer {
width: 400px;
max-width: 500px;
.t-popup__content {
max-height: 400px;
max-width: 500px;
overflow-y: auto;
overflow-x: hidden;
word-wrap: break-word;
word-break: break-word;
}
}
</style>
@@ -0,0 +1,171 @@
<template>
<pre v-if="nestedJson || longText" class="cv-json">{{ nestedJson || longText }}</pre>
<span v-else-if="scalar" class="cv-scalar">{{ scalar }}</span>
<ul v-else-if="primitives" class="cv-primitives">
<li v-for="(item, index) in primitives" :key="index">{{ item }}</li>
</ul>
<div v-else-if="cards" class="cv-cards">
<article v-for="card in cards" :key="card.key" class="cv-card">
<div class="cv-card__title">
<span class="cv-index">#{{ card.index }}</span>
<span>{{ card.title }}</span>
</div>
<dl v-if="card.fields.length" class="cv-object">
<div v-for="field in card.fields" :key="field.key" class="cv-row">
<dt>{{ field.key }}</dt>
<dd><CatalogValue :value="field.value" :depth="depth + 1" /></dd>
</div>
</dl>
</article>
</div>
<div v-else-if="items" class="cv-list">
<div v-for="(item, index) in items" :key="index" class="cv-list__item">
<CatalogValue :value="item" :depth="depth + 1" />
</div>
</div>
<dl v-else-if="fields" class="cv-object">
<div v-for="field in fields" :key="field.key" class="cv-row">
<dt>{{ field.key }}</dt>
<dd><CatalogValue :value="field.value" :depth="depth + 1" /></dd>
</div>
</dl>
</template>
<script setup lang="ts">
import { computed } from 'vue'
const TITLE_KEYS = ['title', 'name', 'question', 'summary', 'slug', 'path', 'id']
const props = withDefaults(defineProps<{
value: unknown
depth?: number
}>(), { depth: 0 })
const depth = computed(() => props.depth ?? 0)
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value)
}
function formatScalar(value: unknown): string {
if (value == null || value === '') return '—'
if (typeof value === 'string') return value
if (typeof value === 'number' || typeof value === 'boolean') return String(value)
return ''
}
function isPrimitive(value: unknown): boolean {
return value == null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'
}
function isLongText(value: string): boolean {
return value.includes('\n') || value.length > 180
}
const items = computed(() => Array.isArray(props.value) ? props.value : null)
const recordValue = computed(() => isRecord(props.value) ? props.value : null)
const nestedJson = computed(() => {
if (depth.value < 4 || (items.value == null && recordValue.value == null)) return ''
try {
return JSON.stringify(props.value, null, 2)
} catch {
return String(props.value)
}
})
const longText = computed(() => (
typeof props.value === 'string' && isLongText(props.value) ? props.value : ''
))
const scalar = computed(() => {
if (nestedJson.value || longText.value || items.value || recordValue.value) return ''
return formatScalar(props.value)
})
const primitives = computed(() => {
if (!items.value || items.value.some((item) => !isPrimitive(item))) return null
return items.value.map((item) => formatScalar(item))
})
const cards = computed(() => {
if (!items.value || !items.value.length || items.value.some((item) => !isRecord(item))) return null
return items.value.map((item, index) => {
const row = item as Record<string, unknown>
const titleKey = TITLE_KEYS.find((key) => typeof row[key] === 'string' && String(row[key]).trim()) || ''
const title = titleKey ? String(row[titleKey]).trim() : `#${index + 1}`
const fields = Object.entries(row)
.filter(([key, value]) => key !== titleKey && !isEmpty(value))
.map(([key, value]) => ({ key, value }))
return { key: `${title}-${index}`, index: index + 1, title, fields }
})
})
const fields = computed(() => {
if (!recordValue.value) return null
return Object.entries(recordValue.value)
.filter(([, value]) => !isEmpty(value))
.map(([key, value]) => ({ key, value }))
})
function isEmpty(value: unknown): boolean {
if (value == null) return true
if (typeof value === 'string') return value.trim() === ''
if (Array.isArray(value)) return value.length === 0
if (isRecord(value)) return Object.keys(value).length === 0
return false
}
</script>
<style lang="less" scoped>
.cv-scalar, .cv-primitives li { white-space: pre-wrap; overflow-wrap: anywhere; }
.cv-json {
margin: 0;
padding: 8px 10px;
max-height: 240px;
overflow: auto;
background: var(--td-bg-color-secondarycontainer);
border-radius: var(--app-radius-sm);
font: var(--app-text-sm)/1.55 var(--app-font-family-mono, monospace);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.cv-primitives, .cv-list { margin: 0; padding: 0; list-style: none; }
.cv-primitives li + li, .cv-list__item + .cv-list__item { margin-top: 4px; }
.cv-cards { display: flex; flex-direction: column; gap: 8px; }
.cv-card {
padding: 8px 10px;
border: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-md);
background: var(--td-bg-color-container);
}
.cv-card__title {
display: flex;
align-items: baseline;
gap: 8px;
min-width: 0;
font-weight: 600;
overflow-wrap: anywhere;
}
.cv-index {
flex-shrink: 0;
font-size: var(--app-text-xs);
font-weight: 600;
color: var(--td-text-color-placeholder);
}
.cv-object { margin: 6px 0 0; }
.cv-row {
display: grid;
grid-template-columns: minmax(88px, 28%) minmax(0, 1fr);
gap: 8px;
padding: 4px 0;
}
.cv-row + .cv-row { border-top: 1px solid var(--td-component-stroke); }
.cv-row dt {
margin: 0;
color: var(--td-text-color-placeholder);
font: var(--app-text-sm)/1.5 var(--app-font-family-mono, monospace);
overflow-wrap: anywhere;
}
.cv-row dd { margin: 0; min-width: 0; }
</style>
@@ -0,0 +1,75 @@
<template>
<div class="chunk-detail">
<div class="info-section">
<div class="info-field">
<span class="field-label">{{ $t('chat.chunkIdLabel') }}</span>
<span class="field-value"><code>{{ data.chunk_id }}</code></span>
</div>
<div class="info-field">
<span class="field-label">{{ $t('chat.documentIdLabel') }}</span>
<span class="field-value"><code>{{ data.knowledge_id }}</code></span>
</div>
<div class="info-field">
<span class="field-label">{{ $t('chat.positionLabel') }}</span>
<span class="field-value">{{ $t('chat.chunkPositionValue', { index: data.chunk_index }) }}</span>
</div>
<div v-if="data.content_length" class="info-field">
<span class="field-label">{{ $t('chat.contentLengthLabelSimple') }}</span>
<span class="field-value">{{ $t('chat.lengthChars', { value: data.content_length }) }}</span>
</div>
</div>
<div class="info-section">
<div class="info-section-title">{{ $t('chat.fullContentLabel') }}</div>
<div class="full-content">{{ data.content }}</div>
</div>
<div class="info-section">
<div class="action-buttons">
<button class="action-button" @click="copyToClipboard">
📋 {{ $t('chat.copyContent') }}
</button>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import type { ChunkDetailData } from '@/types/tool-results';
import { useI18n } from 'vue-i18n';
import { copyToClipboard as copyTextToClipboard } from '@/utils/clipboard';
const props = defineProps<{
data: ChunkDetailData;
}>();
const { t } = useI18n();
const copyToClipboard = () => {
void copyTextToClipboard(props.data.content);
};
</script>
<style lang="less" scoped>
@import './tool-results.less';
.chunk-detail {
display: flex;
flex-direction: column;
gap: 12px;
padding: 8px 0;
}
code {
font-family: var(--app-font-family-mono);
font-size: var(--app-text-xs);
background: var(--td-bg-color-secondarycontainer);
padding: 2px 4px;
border-radius: 3px;
}
.action-buttons {
display: flex;
gap: 8px;
}
</style>
@@ -0,0 +1,167 @@
<template>
<div class="popup-content">
<div class="popup-content-wrapper">
<!-- Pre-rendered HTML (already sanitized upstream) -->
<div v-if="isHtml" class="full-content html-content" v-html="processedContent"></div>
<!-- Merged chunks from the same document -->
<template v-else-if="blocks.length > 1">
<div v-for="(block, idx) in blocks" :key="block.chunk_id || idx" class="chunk-block">
<div class="chunk-block__label">{{ $t('chat.chunkOrdinal', { index: idx + 1 }) }}</div>
<div class="full-content" v-html="block.html"></div>
</div>
</template>
<!-- Single chunk -->
<div v-else-if="blocks.length === 1" class="full-content" v-html="blocks[0].html"></div>
</div>
<div v-if="hasInfo" class="popup-footer">
<span v-if="chunkId" class="popup-footer__item" :title="chunkId">
<span class="popup-footer__key">{{ $t('chat.chunkIdLabel') }}</span>{{ chunkId }}
</span>
<span v-if="knowledgeId" class="popup-footer__item" :title="knowledgeId">
<span class="popup-footer__key">{{ $t('chat.documentIdLabel') }}</span>{{ knowledgeId }}
</span>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import { sanitizeHTML } from '@/utils/security';
import { highlightText, highlightRegex } from '@/components/GlobalCommandPalette/useHighlight';
import { cleanContent } from './contentClean';
interface ChunkContent {
content: string;
chunk_id?: string;
knowledge_id?: string;
}
interface Props {
content?: string;
chunks?: ChunkContent[];
chunkId?: string;
knowledgeId?: string;
highlight?: string;
// When true, `highlight` is treated as a regex (e.g. grep's "a|b|c"),
// otherwise as whitespace-separated literal terms.
regex?: boolean;
isHtml?: boolean;
}
const props = defineProps<Props>();
const hasInfo = computed(() => !!(props.chunkId || props.knowledgeId));
const processedContent = computed(() => {
if (!props.content) return '';
return props.isHtml ? sanitizeHTML(props.content) : props.content;
});
const renderBlock = (raw: string): string => {
const cleaned = cleanContent(raw);
const pattern = props.highlight ?? '';
return props.regex ? highlightRegex(cleaned, pattern) : highlightText(cleaned, pattern);
};
const blocks = computed(() => {
const source: ChunkContent[] = props.chunks?.length
? props.chunks
: props.content
? [{ content: props.content, chunk_id: props.chunkId, knowledge_id: props.knowledgeId }]
: [];
return source
.map((c) => ({ chunk_id: c.chunk_id, html: renderBlock(c.content) }))
.filter((b) => b.html.trim() !== '');
});
</script>
<style lang="less" scoped>
.popup-content {
display: flex;
flex-direction: column;
max-height: 420px;
max-width: 500px;
border: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-md);
background: var(--td-bg-color-container);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
word-wrap: break-word;
word-break: break-word;
overflow: hidden;
.popup-content-wrapper {
flex: 1;
overflow-y: auto;
overflow-x: hidden;
padding: 14px;
min-height: 0;
}
.full-content {
font-size: var(--app-text-md);
color: var(--td-text-color-primary);
line-height: 1.7;
white-space: pre-wrap;
word-break: break-word;
&.html-content {
white-space: normal;
:deep(p) {
margin: 8px 0;
line-height: 1.7;
}
}
}
.chunk-block {
& + & {
margin-top: 12px;
padding-top: 12px;
border-top: 1px dashed var(--td-component-stroke);
}
.chunk-block__label {
font-size: var(--app-text-xs);
font-weight: 600;
color: var(--td-text-color-placeholder);
margin-bottom: 4px;
}
}
:deep(.search-highlight) {
background: rgba(255, 213, 0, 0.35);
color: inherit;
padding: 0 1px;
border-radius: 2px;
font-weight: 500;
}
.popup-footer {
flex-shrink: 0;
display: flex;
flex-direction: column;
gap: 2px;
padding: 8px 14px;
border-top: 1px solid var(--td-component-stroke);
}
.popup-footer__item {
font-family: var(--app-font-family-mono);
font-size: var(--app-text-2xs);
color: var(--td-text-color-placeholder);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.popup-footer__key {
margin-right: 4px;
font-family: inherit;
color: var(--td-text-color-disabled);
}
}
</style>
@@ -0,0 +1,130 @@
<template>
<div class="database-query-display">
<!-- Results Summary -->
<!-- Results Table -->
<div v-if="data.rows && data.rows.length > 0" class="results-table-container">
<table class="results-table">
<thead>
<tr>
<th v-for="column in data.columns" :key="column">{{ column }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in data.rows" :key="index">
<td v-for="column in data.columns" :key="column">
{{ formatValue(row[column]) }}
</td>
</tr>
</tbody>
</table>
</div>
<!-- No Results -->
<div v-else class="no-results">
{{ $t('chat.noDatabaseRecords') }}
</div>
</div>
</template>
<script setup lang="ts">
import type { DatabaseQueryData } from '@/types/tool-results';
import { useI18n } from 'vue-i18n';
interface Props {
data: DatabaseQueryData;
}
const props = defineProps<Props>();
const { t } = useI18n();
const formatValue = (value: any): string => {
if (value === null || value === undefined) {
return t('chat.nullValuePlaceholder');
}
if (typeof value === 'object') {
return JSON.stringify(value);
}
return String(value);
};
</script>
<style lang="less" scoped>
.database-query-display {
font-size: var(--app-text-md);
color: var(--td-text-color-primary);
}
.results-summary {
padding: 10px 12px;
background: var(--td-brand-color-light);
border-left: 3px solid var(--td-brand-color);
border-radius: var(--app-radius-xs);
margin-bottom: 16px;
font-size: var(--app-text-md);
strong {
color: var(--td-brand-color);
font-weight: 600;
}
}
.results-table-container {
overflow-x: auto;
border: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-sm);
background: var(--td-bg-color-container);
}
.results-table {
width: 100%;
border-collapse: collapse;
font-size: var(--app-text-sm);
thead {
background: var(--td-bg-color-secondarycontainer);
border-bottom: 2px solid var(--td-component-stroke);
th {
padding: 10px 12px;
text-align: left;
font-weight: 600;
color: var(--td-text-color-primary);
white-space: nowrap;
}
}
tbody {
tr {
border-bottom: 1px solid var(--td-component-stroke);
&:hover {
background: var(--td-bg-color-secondarycontainer);
}
&:last-child {
border-bottom: none;
}
}
td {
padding: 10px 12px;
color: var(--td-text-color-primary);
vertical-align: top;
max-width: 400px;
overflow: hidden;
text-overflow: ellipsis;
}
}
}
.no-results {
padding: 32px;
text-align: center;
color: var(--td-text-color-placeholder);
font-style: italic;
background: var(--td-bg-color-secondarycontainer);
border-radius: var(--app-radius-sm);
border: 1px solid var(--td-component-stroke);
}
</style>
@@ -0,0 +1,158 @@
<template>
<div v-if="source !== undefined" class="doc-md">
<DocMarkdown v-for="(block, index) in blocks" :key="index" :token="block" />
</div>
<component
v-else-if="token?.type === 'heading'"
:is="headingTag"
:class="`doc-h doc-h-${token.depth || 2}`"
>
<DocMarkdown v-for="(child, index) in inline(token)" :key="index" :token="child" />
</component>
<p v-else-if="token?.type === 'paragraph'">
<DocMarkdown v-for="(child, index) in inline(token)" :key="index" :token="child" />
</p>
<blockquote v-else-if="token?.type === 'blockquote'">
<DocMarkdown v-for="(child, index) in token.tokens || []" :key="index" :token="child" />
</blockquote>
<component
:is="token?.ordered ? 'ol' : 'ul'"
v-else-if="token?.type === 'list'"
>
<li v-for="(item, index) in token.items || []" :key="index">
<DocMarkdown v-for="(child, childIndex) in item.tokens || []" :key="childIndex" :token="child" />
</li>
</component>
<pre v-else-if="token?.type === 'code'" class="doc-code"><code>{{ token.text }}</code></pre>
<table v-else-if="token?.type === 'table'">
<thead>
<tr>
<th v-for="(cell, index) in token.header || []" :key="index">
<DocMarkdown v-for="(child, childIndex) in inline(cell)" :key="childIndex" :token="child" />
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in token.rows || []" :key="index">
<td v-for="(cell, cellIndex) in row" :key="cellIndex">
<DocMarkdown v-for="(child, childIndex) in inline(cell)" :key="childIndex" :token="child" />
</td>
</tr>
</tbody>
</table>
<hr v-else-if="token?.type === 'hr'" />
<a
v-else-if="token?.type === 'link' && linkHref"
:href="linkHref"
target="_blank"
rel="noopener noreferrer"
>
<DocMarkdown v-for="(child, index) in inline(token)" :key="index" :token="child" />
</a>
<span v-else-if="token?.type === 'link'">{{ token.text }}</span>
<strong v-else-if="token?.type === 'strong'">
<DocMarkdown v-for="(child, index) in inline(token)" :key="index" :token="child" />
</strong>
<em v-else-if="token?.type === 'em'">
<DocMarkdown v-for="(child, index) in inline(token)" :key="index" :token="child" />
</em>
<code v-else-if="token?.type === 'codespan'">{{ token.text }}</code>
<template v-else-if="token?.type === 'text' && token.tokens?.length">
<DocMarkdown v-for="(child, index) in token.tokens" :key="index" :token="child" />
</template>
<template v-else-if="token?.type === 'text' || token?.type === 'escape' || token?.type === 'html' || token?.type === 'image'">{{ token.text }}</template>
<template v-else-if="token?.type === 'space' || token?.type === 'br'" />
<template v-else>{{ token?.text || '' }}</template>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { marked } from 'marked'
import { safeDocUrl } from '@/utils/catalogToolDisplay'
type MdToken = {
type: string
text?: string
depth?: number
href?: string
ordered?: boolean
tokens?: MdToken[]
items?: MdToken[]
header?: MdToken[]
rows?: MdToken[][]
}
const props = defineProps<{
source?: string
token?: MdToken
}>()
const blocks = computed(() => (
props.source != null ? marked.lexer(props.source) as MdToken[] : []
))
const headingTag = computed(() => {
const depth = Math.min(6, Math.max(1, props.token?.depth || 2))
return `h${depth}`
})
const linkHref = computed(() => safeDocUrl(props.token?.href || ''))
function inline(token: MdToken): MdToken[] {
if (token.tokens?.length) return token.tokens
if (token.text) return [{ type: 'text', text: token.text }]
return []
}
</script>
<style lang="less" scoped>
.doc-md {
max-height: 360px;
overflow: auto;
font-size: var(--app-text-sm);
line-height: 1.6;
color: var(--td-text-color-primary);
overflow-wrap: anywhere;
}
.doc-md :deep(p) { margin: 0 0 8px; }
.doc-md :deep(ul), .doc-md :deep(ol) { margin: 0 0 8px; padding-left: 1.2em; }
.doc-md :deep(li + li) { margin-top: 2px; }
.doc-md :deep(.doc-h) { margin: 10px 0 6px; font-weight: 600; line-height: 1.4; }
.doc-md :deep(.doc-h-1), .doc-md :deep(.doc-h-2) { font-size: var(--app-text-md); }
.doc-md :deep(a) { color: var(--td-brand-color); }
.doc-md :deep(code) {
padding: 0 4px;
border-radius: var(--app-radius-xs);
background: var(--td-bg-color-secondarycontainer);
font-family: var(--app-font-family-mono, monospace);
font-size: var(--app-text-sm);
}
.doc-md :deep(.doc-code) {
margin: 0 0 8px;
padding: 8px 10px;
max-height: 220px;
overflow: auto;
background: var(--td-bg-color-secondarycontainer);
border-radius: var(--app-radius-sm);
font: var(--app-text-sm)/1.55 var(--app-font-family-mono, monospace);
white-space: pre-wrap;
}
.doc-md :deep(.doc-code code) { padding: 0; background: transparent; }
.doc-md :deep(blockquote) {
margin: 0 0 8px;
padding-left: 10px;
border-left: 2px solid var(--td-component-stroke);
color: var(--td-text-color-secondary);
}
.doc-md :deep(table) {
width: 100%;
margin: 0 0 8px;
border-collapse: collapse;
font-size: var(--app-text-xs);
}
.doc-md :deep(th), .doc-md :deep(td) {
padding: 4px 8px;
border: 1px solid var(--td-component-stroke);
text-align: left;
vertical-align: top;
}
.doc-md :deep(hr) { border: 0; border-top: 1px solid var(--td-component-stroke); margin: 8px 0; }
</style>
@@ -0,0 +1,314 @@
<template>
<div class="document-info">
<div v-if="documents.length" class="documents-list">
<div
v-for="(doc, index) in documents"
:key="doc.faq_id || doc.knowledge_id || index"
class="result-card document-card"
>
<div class="result-header document-header">
<div class="result-title">
<span class="doc-index">#{{ index + 1 }}</span>
<span class="doc-title">{{ doc.title || $t('chat.notProvided') }}</span>
</div>
<div class="result-meta">
<span class="meta-chip" v-if="doc.chunk_count">
{{ $t('chat.chunkCountValue', { count: doc.chunk_count }) }}
</span>
</div>
</div>
<div class="result-content expanded">
<div class="info-section">
<div class="info-field" v-if="doc.is_faq && doc.faq_id">
<span class="field-label">{{ $t('chat.faqIdLabel') }}</span>
<span class="field-value"><code>{{ doc.faq_id }}</code></span>
</div>
<div class="info-field" v-if="doc.knowledge_id">
<span class="field-label">{{ doc.is_faq ? $t('chat.faqContainerIdLabel') : $t('chat.documentIdLabel') }}</span>
<span class="field-value"><code>{{ doc.knowledge_id }}</code></span>
</div>
<div
v-if="doc.is_faq && doc.faq_answers?.length"
class="info-field info-field--block"
>
<span class="field-label">{{ $t('chat.faqAnswersLabel') }}</span>
<ul class="faq-answers-list">
<li v-for="(ans, aIdx) in doc.faq_answers" :key="aIdx">{{ ans }}</li>
</ul>
</div>
<div class="info-field" v-if="doc.description">
<span class="field-label">{{ $t('chat.documentDescriptionLabel') }}</span>
<span class="field-value">{{ doc.description }}</span>
</div>
<div class="info-field" v-if="doc.source || doc.type">
<span class="field-label">{{ $t('chat.documentSourceLabel') }}</span>
<span class="field-value">{{ formatSource(doc) }}</span>
</div>
<div class="info-field" v-if="doc.channel && doc.channel !== 'web'">
<span class="field-label">{{ $t('knowledgeBase.channelLabel') }}</span>
<span class="field-value">{{ getChannelLabel(doc.channel) }}</span>
</div>
<div class="info-field" v-if="doc.file_name || doc.file_type || doc.file_size">
<span class="field-label">{{ $t('chat.documentFileLabel') }}</span>
<span class="field-value">
<span v-if="doc.file_name">{{ doc.file_name }}</span>
<template v-if="doc.file_type">&nbsp;({{ doc.file_type }})</template>
<template v-if="doc.file_size">&nbsp;· {{ formatFileSize(doc.file_size) }}</template>
</span>
</div>
</div>
<div
v-if="doc.metadata && Object.keys(doc.metadata).length"
class="info-section metadata-section"
>
<div class="info-section-title">{{ $t('chat.documentMetadataLabel') }}</div>
<ul class="metadata-list">
<li
v-for="(value, key) in doc.metadata"
:key="`${doc.knowledge_id}-${key}`"
>
<span class="metadata-key">{{ key }}:</span>
<span class="metadata-value">{{ formatMetadataValue(value) }}</span>
</li>
</ul>
</div>
</div>
</div>
</div>
<div v-else class="empty-state">
{{ $t('chat.documentInfoEmpty') }}
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { DocumentInfoData, DocumentInfoDocument } from '@/types/tool-results';
const props = defineProps<{
data: DocumentInfoData;
}>();
const { t } = useI18n();
const documents = computed(() => props.data?.documents ?? []);
const errors = computed(() => props.data?.errors?.filter(Boolean) ?? []);
const totalChunkCount = computed(() =>
documents.value.reduce((sum, doc) => sum + (doc.chunk_count || 0), 0),
);
const channelLabelMap: Record<string, string> = {
web: 'knowledgeBase.channelWeb',
api: 'knowledgeBase.channelApi',
browser_extension: 'knowledgeBase.channelBrowserExtension',
wechat: 'knowledgeBase.channelWechat',
wecom: 'knowledgeBase.channelWecom',
feishu: 'knowledgeBase.channelFeishu',
gitlab: 'knowledgeBase.channelGitLab',
seafile: 'knowledgeBase.channelSeafile',
confluence: 'knowledgeBase.channelConfluence',
dingtalk: 'knowledgeBase.channelDingtalk',
slack: 'knowledgeBase.channelSlack',
im: 'knowledgeBase.channelIm',
ima: 'knowledgeBase.channelIma',
};
const getChannelLabel = (channel: string) => {
const key = channelLabelMap[channel];
return key ? t(key) : t('knowledgeBase.channelUnknown');
};
const formatSource = (doc: DocumentInfoDocument) => {
if (doc.type && doc.source) {
return `${doc.type} · ${doc.source}`;
}
return doc.source || doc.type || t('chat.notProvided');
};
const formatFileSize = (size?: number) => {
if (!size || size <= 0) {
return t('chat.notProvided');
}
const units = ['B', 'KB', 'MB', 'GB'];
let value = size;
let unitIndex = 0;
while (value >= 1024 && unitIndex < units.length - 1) {
value /= 1024;
unitIndex += 1;
}
const fixed = value >= 10 || unitIndex === 0 ? 0 : 1;
return `${value.toFixed(fixed)} ${units[unitIndex]}`;
};
const formatMetadataValue = (value: unknown) => {
if (value === null || value === undefined) {
return t('chat.notProvided');
}
if (typeof value === 'object') {
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
return String(value);
};
</script>
<style lang="less" scoped>
@import './tool-results.less';
.document-info {
display: flex;
flex-direction: column;
gap: 8px;
}
.meta-chip {
font-size: var(--app-text-xs);
color: var(--td-text-color-secondary);
background: var(--td-bg-color-secondarycontainer);
border: 1px solid @card-border;
border-radius: var(--app-radius-lg);
padding: 2px 8px;
line-height: 1.5;
white-space: nowrap;
}
.documents-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.document-card {
margin: 0 8px 8px 8px;
.document-header {
align-items: center;
}
.doc-index {
font-weight: 600;
color: var(--td-brand-color);
}
.doc-title {
font-size: var(--app-text-md);
font-weight: 500;
color: var(--td-text-color-primary);
}
.status-pill {
font-size: var(--app-text-xs);
color: var(--td-brand-color);
border: 1px solid color-mix(in srgb, var(--td-brand-color) 30%, transparent);
border-radius: var(--app-radius-lg);
padding: 2px 8px;
line-height: 1.4;
}
}
.info-section {
margin-top: 0;
padding: 6px 0;
&:first-of-type {
padding-top: 4px;
}
}
.faq-answers-list {
list-style: none;
margin: 4px 0 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 4px;
li {
font-size: var(--app-text-sm);
line-height: 1.5;
color: var(--td-text-color-primary);
}
}
.info-field {
display: flex;
gap: 10px;
margin-bottom: 5px;
font-size: var(--app-text-sm);
line-height: 1.5;
&--block {
flex-direction: column;
gap: 4px;
}
.field-label {
color: var(--td-text-color-secondary);
min-width: 90px;
font-weight: 500;
}
.field-value {
flex: 1;
color: var(--td-text-color-primary);
line-height: 1.5;
}
}
.metadata-section {
padding-top: 10px;
border-top: 1px dashed @card-border;
}
.metadata-list {
list-style: none;
margin: 4px 0 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 3px;
li {
font-size: var(--app-text-xs);
color: var(--td-text-color-primary);
line-height: 1.5;
}
.metadata-key {
font-weight: 600;
margin-right: 4px;
color: var(--td-text-color-secondary);
}
.metadata-value {
font-family: var(--app-font-family-mono);
color: var(--td-text-color-primary);
}
}
.empty-state {
font-size: var(--app-text-sm);
color: var(--td-text-color-placeholder);
text-align: center;
padding: 14px;
border: 1px dashed @card-border;
border-radius: @card-radius;
background: var(--td-bg-color-secondarycontainer);
}
code {
font-family: var(--app-font-family-mono);
font-size: var(--app-text-2xs);
background: var(--td-bg-color-secondarycontainer);
padding: 2px 4px;
border-radius: 2px;
color: var(--td-text-color-primary);
}
</style>
@@ -0,0 +1,138 @@
<template>
<div class="graph-query-results">
<!-- Graph Configuration Card -->
<div v-if="data.graph_config" class="stats-card">
<div class="stats-title">{{ $t('chat.graphConfigTitle') }}</div>
<div class="info-field">
<span class="field-label">{{ $t('chat.entityTypesLabel') }}</span>
<span class="field-value">{{ data.graph_config.nodes.join(', ') }}</span>
</div>
<div class="info-field">
<span class="field-label">{{ $t('chat.relationTypesLabel') }}</span>
<span class="field-value">{{ data.graph_config.relations.join(', ') }}</span>
</div>
</div>
<!-- Results List -->
<div v-if="data.results && data.results.length > 0" class="results-list">
<div class="results-header">
{{ $t('chat.graphResultsHeader', { count: data.count }) }}
</div>
<div
v-for="result in data.results"
:key="result.chunk_id"
class="result-card"
>
<div class="result-header" @click="toggleResult(result.chunk_id)">
<div class="result-title">
<span class="result-index">#{{ result.result_index }}</span>
<span class="relevance-badge" :class="getRelevanceClass(result.relevance_level)">
{{ getRelevanceLabel(result.relevance_level) }}
</span>
<span class="knowledge-title">{{ result.knowledge_title }}</span>
</div>
<div class="result-meta">
<span class="score">{{ (result.score * 100).toFixed(0) }}%</span>
<span class="expand-icon" :class="{ expanded: expandedResults.includes(result.chunk_id) }">
▶
</span>
</div>
</div>
<div class="result-content" :class="{ expanded: expandedResults.includes(result.chunk_id) }">
<div class="full-content">{{ result.content }}</div>
</div>
</div>
</div>
<div v-else class="empty-state">
{{ $t('chat.graphNoResults') }}
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import type { GraphQueryResultsData, RelevanceLevel } from '@/types/tool-results';
import { useI18n } from 'vue-i18n';
const props = defineProps<{
data: GraphQueryResultsData;
}>();
const { t } = useI18n();
const expandedResults = ref<string[]>([]);
const toggleResult = (chunkId: string) => {
const index = expandedResults.value.indexOf(chunkId);
if (index > -1) {
expandedResults.value.splice(index, 1);
} else {
expandedResults.value.push(chunkId);
}
};
const getRelevanceClass = (level: RelevanceLevel): string => {
const classMap: Record<RelevanceLevel, string> = {
'High Relevance': 'high',
'Medium Relevance': 'medium',
'Low Relevance': 'low',
'Weak Relevance': 'weak',
};
return classMap[level] || 'weak';
};
const getRelevanceLabel = (level: RelevanceLevel): string => {
const labelMap: Record<RelevanceLevel, string> = {
'High Relevance': t('chat.relevanceHigh'),
'Medium Relevance': t('chat.relevanceMedium'),
'Low Relevance': t('chat.relevanceLow'),
'Weak Relevance': t('chat.relevanceWeak'),
};
return labelMap[level] || level;
};
</script>
<style lang="less" scoped>
@import './tool-results.less';
.graph-query-results {
display: flex;
flex-direction: column;
gap: 12px;
}
.results-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.results-header {
font-size: var(--app-text-md);
font-weight: 600;
color: var(--td-text-color-primary);
padding: 4px 0;
}
.result-index {
font-size: var(--app-text-md);
color: var(--td-text-color-placeholder);
font-weight: 600;
}
.knowledge-title {
font-size: var(--app-text-md);
color: var(--td-text-color-primary);
flex: 1;
}
.score {
font-size: var(--app-text-sm);
color: var(--td-text-color-placeholder);
font-weight: 500;
}
</style>
@@ -0,0 +1,129 @@
<template>
<div class="grep-results">
<div v-if="rows.length" class="results-list">
<ResultRow v-for="(result, index) in rows" :key="result.key" :index="index + 1" :title="result.title"
:meta="result.meta" :popup-key="result.key" :show-popup="result.chunks.length > 0 || !!result.snippet"
:content="result.chunks.length === 1 ? result.snippet : undefined"
:chunks="result.chunks.length > 1 ? result.chunks : undefined" :chunk-id="result.chunkId"
:knowledge-id="result.knowledgeId" :highlight="searchPattern" :regex="true" />
</div>
<div v-else class="empty-state">
{{ $t('chat.noMatchFound') }}
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { cleanSnippet } from './contentClean';
import ResultRow from './ResultRow.vue';
import { groupGrepChunkResults } from '@/utils/grepResultsGroup';
import type { GrepKnowledgeResult, GrepResultsData } from '@/types/tool-results';
const props = defineProps<{
data: GrepResultsData;
}>();
const { t } = useI18n();
const searchPattern = computed(() => props.data.query ?? props.data.patterns?.[0] ?? '');
type GrepRow = {
key: string;
title: string;
meta: string;
snippet: string;
chunks: { content: string; chunk_id: string; knowledge_id: string }[];
chunkId?: string;
knowledgeId?: string;
};
const formatKnowledgeMeta = (result: GrepKnowledgeResult): string => {
const parts: string[] = [];
const chunks = result.chunk_hit_count ?? 0;
if (chunks > 0) {
parts.push(t('agentStream.grepResults.chunkHits', { count: chunks }));
}
const hits = result.total_pattern_hits ?? 0;
if (hits > 0 && hits !== chunks) {
parts.push(t('agentStream.grepResults.keywordHits', { count: hits }));
}
if (result.title_match) {
parts.push(t('agentStream.grepResults.titleMatch'));
}
return parts.join(' · ');
};
const rowFromGroupedChunk = (group: ReturnType<typeof groupGrepChunkResults>[number]): GrepRow => {
const title = group.title || t('knowledge.untitledDocument');
const meta = group.is_faq
? t('agentStream.grepResults.faqEntry')
: formatKnowledgeMeta({
knowledge_id: group.knowledge_id,
knowledge_base_id: '',
knowledge_title: title,
chunk_hit_count: group.chunk_hit_count,
total_pattern_hits: group.chunk_hit_count,
distinct_patterns: 1,
pattern_counts: {},
title_match: group.title_match,
});
return {
key: group.key,
title,
meta,
snippet: cleanSnippet(group.match_snippet),
chunks: group.chunks.map((chunk) => ({
content: cleanSnippet(chunk.content),
chunk_id: chunk.chunk_id,
knowledge_id: chunk.knowledge_id,
})),
chunkId: group.chunks.length === 1 ? group.chunks[0].chunk_id : undefined,
knowledgeId: group.knowledge_id,
};
};
const rowFromKnowledge = (result: GrepKnowledgeResult): GrepRow => ({
key: result.knowledge_id,
title: result.faq_question || result.knowledge_title || t('knowledge.untitledDocument'),
meta: formatKnowledgeMeta(result),
snippet: cleanSnippet(result.match_snippet ?? ''),
chunks: result.match_snippet
? [{
content: cleanSnippet(result.match_snippet ?? ''),
chunk_id: '',
knowledge_id: result.knowledge_id,
}]
: [],
knowledgeId: result.knowledge_id,
});
const rows = computed((): GrepRow[] => {
const chunkRows = props.data.chunk_results;
if (chunkRows?.length) {
return groupGrepChunkResults(chunkRows).map(rowFromGroupedChunk);
}
return (props.data.knowledge_results ?? []).map(rowFromKnowledge);
});
</script>
<style lang="less" scoped>
@import './tool-results.less';
.grep-results {
display: flex;
flex-direction: column;
padding: 0 0 0 12px;
gap: 3px;
}
.results-list {
display: flex;
flex-direction: column;
gap: 3px;
max-height: 200px;
overflow-y: auto;
}
</style>
@@ -0,0 +1,135 @@
<template>
<div class="image-view-result">
<p class="image-view-summary">{{ summary }}</p>
<div v-if="described.length" class="image-view-descriptions">
<div class="image-view-heading">{{ $t('agentStream.imageView.descriptionsHeading') }}</div>
<div v-for="(item, index) in described" :key="index" class="image-view-item">
<div v-if="item.number" class="image-view-label">{{ $t('agentStream.imageView.imageLabel', { n: item.number }) }}</div>
<div v-if="item.text" class="image-view-text">{{ item.text }}</div>
<div v-else class="image-view-missing">{{ $t('agentStream.imageView.noDescription') }}</div>
</div>
</div>
<ul v-if="errors.length" class="image-view-errors">
<li v-for="(error, index) in errors" :key="index">{{ error }}</li>
</ul>
<p v-if="remaining > 0" class="image-view-remaining">
{{ $t('agentStream.imageView.remaining', { count: remaining }) }}
</p>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import type { ImageViewData } from '@/types/tool-results'
const props = defineProps<{
data: ImageViewData | Record<string, unknown>
}>()
const { t } = useI18n()
const record = computed(() => (props.data || {}) as ImageViewData)
// Numbered images belong to a document (attachment://…/images/N); a plain
// image file has none.
const numbers = computed(() =>
Array.isArray(record.value.image_numbers) ? record.value.image_numbers.map(Number) : [],
)
const total = computed(() => Number(record.value.total_images) || 0)
const numbersLabel = computed(() => {
const list = numbers.value
if (list.length === 0) return ''
if (list.length === 1) return String(list[0])
const contiguous = list.every((n, i) => i === 0 || n === list[i - 1] + 1)
return contiguous ? `${list[0]}–${list[list.length - 1]}` : list.join(', ')
})
const summary = computed(() => {
const file = record.value.file_name || record.value.path || ''
if (!numbers.value.length) return t('agentStream.imageView.single', { file })
return t('agentStream.imageView.summary', { file, numbers: numbersLabel.value, total: total.value })
})
const described = computed(() => {
const descriptions = record.value.image_descriptions
if (!Array.isArray(descriptions)) return []
if (numbers.value.length && descriptions.length !== numbers.value.length) return []
return descriptions.map((text, i) => ({ number: numbers.value[i], text: String(text || '').trim() }))
})
const errors = computed(() =>
Array.isArray(record.value.image_errors) ? record.value.image_errors.map(String) : [],
)
const remaining = computed(() => {
const match = /\/images\/(\d+)$/.exec(String(record.value.next_path || ''))
if (!match) return 0
return Math.max(total.value - Number(match[1]) + 1, 0)
})
</script>
<style lang="less" scoped>
.image-view-result {
display: flex;
flex-direction: column;
gap: 10px;
min-width: 0;
font-size: var(--app-text-sm);
line-height: 1.55;
}
.image-view-summary,
.image-view-remaining {
margin: 0;
color: var(--td-text-color-secondary);
}
.image-view-heading {
margin-bottom: 4px;
font-weight: 500;
color: var(--td-text-color-secondary);
}
.image-view-descriptions {
display: flex;
flex-direction: column;
gap: 8px;
max-height: 320px;
overflow: auto;
}
.image-view-item {
padding: 8px 12px;
border: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-sm);
background: var(--td-bg-color-container);
}
.image-view-label {
margin-bottom: 2px;
font-weight: 500;
color: var(--td-text-color-secondary);
}
.image-view-text {
color: var(--td-text-color-primary);
white-space: pre-wrap;
word-break: break-word;
}
.image-view-missing {
color: var(--td-text-color-placeholder);
}
.image-view-errors {
margin: 0;
padding-left: 18px;
color: var(--td-warning-color);
}
</style>
@@ -0,0 +1,106 @@
<template>
<div class="knowledge-base-list">
<div v-if="data.knowledge_bases && data.knowledge_bases.length > 0">
<div class="stats-card">
<div class="stats-title">{{ $t('chat.knowledgeBaseCount', { count: data.count }) }}</div>
</div>
<div class="card-grid">
<div
v-for="kb in data.knowledge_bases"
:key="kb.id"
class="kb-card"
>
<div class="kb-header">
<span class="kb-index">#{{ kb.index }}</span>
<span class="kb-name">{{ kb.name }}</span>
</div>
<div class="kb-body">
<div class="info-field">
<span class="field-label">ID:</span>
<span class="field-value"><code>{{ kb.id }}</code></span>
</div>
<div v-if="kb.description" class="kb-description">
{{ kb.description }}
</div>
</div>
</div>
</div>
</div>
<div v-else class="empty-state">
{{ $t('chat.noKnowledgeBases') }}
</div>
</div>
</template>
<script setup lang="ts">
import type { KnowledgeBaseListData } from '@/types/tool-results';
const props = defineProps<{
data: KnowledgeBaseListData;
}>();
</script>
<style lang="less" scoped>
@import './tool-results.less';
.knowledge-base-list {
display: flex;
flex-direction: column;
gap: 12px;
}
.kb-card {
background: @card-bg;
border: .5px solid @card-border;
border-radius: @card-radius;
padding: 12px;
transition: all var(--app-motion-base) ease;
&:hover {
border-color: @card-hover-border;
box-shadow: @card-shadow-hover;
}
}
.kb-header {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
}
.kb-index {
font-size: var(--app-text-sm);
color: var(--td-text-color-placeholder);
font-weight: 600;
}
.kb-name {
font-size: var(--app-text-base);
font-weight: 600;
color: var(--td-text-color-primary);
}
.kb-body {
display: flex;
flex-direction: column;
gap: 6px;
}
.kb-description {
font-size: var(--app-text-sm);
color: var(--td-text-color-secondary);
line-height: 1.5;
margin-top: 4px;
}
code {
font-family: var(--app-font-family-mono);
font-size: var(--app-text-xs);
background: var(--td-bg-color-secondarycontainer);
padding: 2px 4px;
border-radius: 3px;
}
</style>
@@ -0,0 +1,43 @@
<template>
<!-- Fallback for ToolResultRenderer when used outside AgentStreamDisplay. -->
<div class="knowledge-chunks-list">
<div v-if="summaryHtml" class="results-summary-text" v-html="summaryHtml" />
<div v-else class="empty-state">{{ $t('chat.noMatchFound') }}</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { getKnowledgeChunksSummaryHtml } from '@/utils/knowledgeChunksDisplay';
import type { KnowledgeChunksListData } from '@/types/tool-results';
const props = defineProps<{
data: KnowledgeChunksListData;
}>();
const { t } = useI18n();
const summaryHtml = computed(() => getKnowledgeChunksSummaryHtml(t, props.data));
</script>
<style lang="less" scoped>
.knowledge-chunks-list {
.results-summary-text {
font-size: var(--agent-step-summary-size, 12px);
font-weight: 400;
color: var(--td-text-color-secondary);
line-height: 1.5;
:deep(strong) {
color: var(--td-text-color-secondary);
font-weight: 500;
}
}
.empty-state {
font-size: var(--app-text-md);
color: var(--td-text-color-placeholder);
}
}
</style>
@@ -0,0 +1,262 @@
<template>
<div class="mcp-result">
<div v-if="success === false" class="mcp-error" role="alert">
<t-icon name="error-circle" />
<pre>{{ output || $t('agentStream.mcp.failed') }}</pre>
</div>
<template v-else-if="discovery && isDiscoveryResult">
<template v-if="mode !== 'describe'">
<div class="mcp-summary">
<span v-if="serverName" class="mcp-server">{{ serverName }}</span>
<span>{{ $t('agentStream.mcp.showing', { count: rows.length, total: total }) }}</span>
<span v-if="data.has_more === true"> · {{ $t('agentStream.mcp.moreAvailable') }}</span>
</div>
<p v-if="!rows.length" class="mcp-empty">{{ $t('agentStream.mcp.empty') }}</p>
<div v-else class="mcp-list">
<article v-for="(row, index) in rows" :key="`${row.name}-${index}`" class="mcp-item">
<button
type="button"
class="mcp-item__head"
:disabled="!mcpDescriptionNeedsExpand(row.description)"
:aria-expanded="openIndex === index"
@click="toggleRow(index, row.description)"
>
<span class="mcp-item__index">#{{ index + 1 }}</span>
<code class="mcp-item__name">{{ row.name }}</code>
<span v-if="row.serverName && row.serverName !== serverName" class="mcp-item__meta">{{ row.serverName }}</span>
<span v-else-if="statusLabel(row.status)" class="mcp-item__meta">{{ statusLabel(row.status) }}</span>
<t-icon
v-if="row.description && mcpDescriptionNeedsExpand(row.description)"
class="mcp-item__chevron"
:name="openIndex === index ? 'chevron-up' : 'chevron-down'"
/>
</button>
<p
v-if="row.description"
:class="['mcp-item__desc', { 'is-open': openIndex === index }]"
>{{ openIndex === index ? row.description : mcpDescriptionLead(row.description) }}</p>
</article>
</div>
</template>
<template v-else>
<div class="mcp-define">
<div class="mcp-define__head">
<code v-if="typeof data.name === 'string' && data.name">{{ data.name }}</code>
<span v-if="serverName" class="mcp-server">{{ serverName }}</span>
</div>
<p
v-if="description"
:class="['mcp-define__desc', { 'is-collapsed': !descOpen && descriptionLong }]"
>{{ description }}</p>
<button
v-if="descriptionLong"
type="button"
class="mcp-toggle"
:aria-expanded="descOpen"
@click="descOpen = !descOpen"
>{{ $t(descOpen ? 'agentStream.mcp.collapse' : 'agentStream.mcp.expand') }}</button>
<div v-if="parameters.length" class="mcp-parameters">
<div class="mcp-parameters__label">{{ $t('agentStream.mcp.parameters') }}</div>
<div v-for="parameter in parameters" :key="parameter.name" class="mcp-parameter">
<div class="mcp-parameter-title">
<code>{{ parameter.name }}</code>
<span v-if="parameter.type">{{ parameter.type }}</span>
<span v-if="parameter.required" class="mcp-required">{{ $t('agentStream.mcp.required') }}</span>
</div>
<p v-if="parameter.description">{{ parameter.description }}</p>
</div>
</div>
<details v-if="data.input_schema !== undefined" class="mcp-definition">
<summary>{{ $t('agentStream.mcp.fullSchema') }}</summary>
<pre>{{ JSON.stringify(data.input_schema, null, 2) }}</pre>
</details>
</div>
</template>
</template>
<div v-else class="mcp-output">
<div class="mcp-summary">{{ $t('agentStream.mcp.result') }}</div>
<pre>{{ output }}</pre>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import {
mcpDescriptionLead,
mcpDescriptionNeedsExpand,
mcpDiscoveryRows,
mcpSchemaParameters,
parseMcpDiscovery,
} from '@/utils/mcpToolDisplay'
const props = withDefaults(defineProps<{
discovery: boolean
output: string
data?: Record<string, unknown>
arguments?: Record<string, unknown>
success?: boolean
}>(), { success: undefined })
const { t, te } = useI18n()
const data = computed(() => parseMcpDiscovery(props.output, props.data))
const mode = computed(() => data.value.mode || props.arguments?.mode || ('input_schema' in data.value ? 'describe' : ''))
const isDiscoveryResult = computed(() => Array.isArray(data.value.servers) || Array.isArray(data.value.tools) ||
typeof data.value.total === 'number' || 'input_schema' in data.value)
const rows = computed(() => mcpDiscoveryRows({ ...data.value, mode: mode.value }))
const serverName = computed(() => {
if (typeof data.value.server_name === 'string' && data.value.server_name) return data.value.server_name
return rows.value.find(row => row.serverName)?.serverName || ''
})
const total = computed(() => typeof data.value.total === 'number' ? data.value.total : rows.value.length)
const parameters = computed(() => mcpSchemaParameters(data.value.input_schema))
const description = computed(() => typeof data.value.description === 'string' ? data.value.description : '')
const descriptionLong = computed(() => mcpDescriptionNeedsExpand(description.value))
const openIndex = ref(-1)
const descOpen = ref(false)
watch(() => props.output, () => {
openIndex.value = -1
descOpen.value = false
})
function toggleRow(index: number, description: string) {
if (!description) return
if (!mcpDescriptionNeedsExpand(description)) return
openIndex.value = openIndex.value === index ? -1 : index
}
const statusLabel = (status: string) => {
if (!status) return ''
const key = `agentStream.mcp.status.${status}`
return te(key) ? t(key) : status
}
</script>
<style lang="less" scoped>
.mcp-result { min-width: 0; font-size: var(--app-text-sm); color: var(--td-text-color-primary); }
.mcp-summary { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; margin-bottom: 8px; color: var(--td-text-color-secondary); }
.mcp-server { font-weight: 600; color: var(--td-text-color-primary); }
.mcp-empty { margin: 0; color: var(--td-text-color-placeholder); }
.mcp-list {
border: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-md);
overflow: hidden;
background: var(--td-bg-color-container);
}
.mcp-item + .mcp-item { border-top: 1px solid var(--td-component-stroke); }
.mcp-item__head {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
margin: 0;
padding: 8px 10px 0;
border: 0;
background: transparent;
font: inherit;
color: inherit;
text-align: left;
cursor: pointer;
}
.mcp-item__head:disabled { cursor: default; }
.mcp-item__head:not(:disabled):hover .mcp-item__name { color: var(--td-brand-color); }
.mcp-item__index {
flex-shrink: 0;
min-width: 22px;
font-size: var(--app-text-xs);
font-weight: 600;
color: var(--td-text-color-placeholder);
}
.mcp-item__name {
flex: 1;
min-width: 0;
font: 12px/1.5 var(--app-font-family-mono, monospace);
font-weight: 600;
color: var(--td-text-color-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.mcp-item__meta {
flex-shrink: 0;
font-size: var(--app-text-xs);
color: var(--td-text-color-placeholder);
}
.mcp-item__chevron {
flex-shrink: 0;
color: var(--td-text-color-placeholder);
}
.mcp-item__desc {
margin: 4px 10px 10px 40px;
font-size: var(--app-text-sm);
line-height: 1.55;
color: var(--td-text-color-secondary);
overflow-wrap: anywhere;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.mcp-item__desc.is-open {
display: block;
white-space: pre-wrap;
max-height: 240px;
overflow: auto;
}
.mcp-define__head {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 6px;
}
.mcp-define__head code {
font: 12px/1.5 var(--app-font-family-mono, monospace);
font-weight: 600;
}
.mcp-define__head .mcp-server { font-weight: 500; color: var(--td-text-color-secondary); }
.mcp-define__desc {
margin: 0;
line-height: 1.65;
color: var(--td-text-color-secondary);
overflow-wrap: anywhere;
white-space: pre-wrap;
}
.mcp-define__desc.is-collapsed {
white-space: normal;
display: -webkit-box;
-webkit-line-clamp: 4;
-webkit-box-orient: vertical;
overflow: hidden;
}
.mcp-toggle {
margin: 6px 0 0;
padding: 0;
border: 0;
background: transparent;
font: inherit;
font-size: var(--app-text-sm);
color: var(--td-brand-color);
cursor: pointer;
}
.mcp-parameters { margin-top: 10px; border: 1px solid var(--td-component-stroke); border-radius: var(--app-radius-md); overflow: hidden; }
.mcp-parameters__label {
padding: 6px 12px;
font-size: var(--app-text-xs);
font-weight: 600;
color: var(--td-text-color-placeholder);
background: var(--td-bg-color-secondarycontainer);
}
.mcp-parameter { padding: 8px 12px; }
.mcp-parameter + .mcp-parameter { border-top: 1px solid var(--td-component-stroke); }
.mcp-parameter-title { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; overflow-wrap: anywhere; }
.mcp-parameter-title code { font-weight: 600; }
.mcp-parameter-title span { color: var(--td-text-color-secondary); }
.mcp-parameter-title .mcp-required { color: var(--td-brand-color); }
.mcp-parameter p { margin: 4px 0 0; color: var(--td-text-color-secondary); white-space: pre-wrap; overflow-wrap: anywhere; }
.mcp-definition { margin-top: 10px; }
.mcp-definition summary { cursor: pointer; color: var(--td-text-color-secondary); }
pre { margin: 8px 0 0; padding: 10px 12px; background: var(--td-bg-color-secondarycontainer); border-radius: var(--app-radius-sm); font: 12px/1.6 var(--app-font-family-mono); white-space: pre-wrap; overflow-wrap: anywhere; max-height: 320px; overflow: auto; }
.mcp-error { display: flex; align-items: flex-start; gap: 8px; color: var(--td-error-color); }
.mcp-error pre { margin: 0; flex: 1; min-width: 0; }
</style>
@@ -0,0 +1,216 @@
<template>
<div class="catalog-result">
<div v-if="plainError" class="catalog-error" role="alert">
<t-icon name="error-circle" />
<pre>{{ plainError }}</pre>
</div>
<template v-else-if="mode === 'find'">
<div class="catalog-summary">
<span>{{ $t('agentStream.operations.found', { count: operations.length }) }}</span>
<span v-if="unavailable.length"> · {{ $t('agentStream.operations.unavailableCount', { count: unavailable.length }) }}</span>
</div>
<p v-if="!operations.length && !unavailable.length" class="catalog-empty">{{ $t('agentStream.operations.empty') }}</p>
<div v-if="operations.length" class="catalog-list">
<article v-for="(op, index) in operations" :key="`${op.id}-${index}`" class="catalog-item">
<div class="catalog-item__head catalog-item__head--static">
<span class="catalog-item__index">#{{ index + 1 }}</span>
<span class="catalog-item__name" :title="op.id">{{ getOperationLabel(t, op.id) }}</span>
<span v-if="op.risk" class="catalog-risk" :data-risk="op.risk">{{ riskLabel(op.risk) }}</span>
<span class="catalog-item__summary">{{ op.summary }}</span>
</div>
<div v-if="op.expandable" class="catalog-item__body">
<p v-if="op.description">{{ op.description }}</p>
<div v-if="op.params.length" class="catalog-params">
<div class="catalog-params__label">{{ $t('agentStream.operations.parameters') }}</div>
<div v-for="param in op.params" :key="param.name" class="catalog-param">
<div class="catalog-param__title">
<code>{{ param.name }}</code>
<span v-if="param.type">{{ param.type }}</span>
<span v-if="param.required" class="catalog-required">{{ $t('agentStream.operations.required') }}</span>
</div>
<p v-if="param.description">{{ param.description }}</p>
<p v-if="param.enumText" class="catalog-param__meta">{{ $t('agentStream.operations.enum') }}:{{ param.enumText }}</p>
<p v-if="param.range" class="catalog-param__meta">{{ $t('agentStream.operations.range', param.range) }}</p>
</div>
</div>
</div>
</article>
</div>
<div v-if="unavailable.length" class="catalog-unavailable">
<div class="catalog-summary">{{ $t('agentStream.operations.unavailableHeading') }}</div>
<div class="catalog-list">
<article v-for="(op, index) in unavailable" :key="`${op.id}-${index}`" class="catalog-item">
<div class="catalog-item__head catalog-item__head--static">
<span class="catalog-item__index">#{{ index + 1 }}</span>
<span class="catalog-item__name" :title="op.id">{{ getOperationLabel(t, op.id) }}</span>
<span v-if="op.risk" class="catalog-risk" :data-risk="op.risk">{{ riskLabel(op.risk) }}</span>
<span class="catalog-item__summary">{{ op.summary }}</span>
</div>
<p v-if="op.reason" class="catalog-item__reason">{{ op.reason }}</p>
</article>
</div>
</div>
</template>
<template v-else>
<div v-if="run.operation || run.truncated" class="catalog-summary">
<span v-if="run.operation" class="catalog-operation-name" :title="run.operation">{{ getOperationLabel(t, run.operation) }}</span>
<span v-if="run.truncated">{{ $t('agentStream.operations.truncated') }}</span>
</div>
<p v-if="resultEmpty" class="catalog-empty">{{ $t('agentStream.operations.emptyResult') }}</p>
<CatalogValue v-else :value="run.data" />
<div v-if="hasMeta" class="catalog-meta">
<div class="catalog-summary">{{ $t('agentStream.operations.meta') }}</div>
<CatalogValue :value="run.meta" />
</div>
</template>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import {
getOperationLabel,
isEmptyCatalogValue,
operationRows,
parseCatalogPayload,
runOperationView,
unavailableOperationRows,
} from '@/utils/catalogToolDisplay'
import CatalogValue from './CatalogValue.vue'
const props = withDefaults(defineProps<{
mode: 'find' | 'run'
output?: string
data?: Record<string, unknown>
success?: boolean
}>(), { output: '', success: undefined })
const { t, te } = useI18n()
const payload = computed(() => parseCatalogPayload(props.output, props.data))
const operations = computed(() => operationRows(payload.value))
const unavailable = computed(() => unavailableOperationRows(payload.value))
const run = computed(() => runOperationView(payload.value))
const resultEmpty = computed(() => isEmptyCatalogValue(run.value.data))
const hasMeta = computed(() => !isEmptyCatalogValue(run.value.meta))
const plainError = computed(() => {
if (props.success !== false) return ''
if (props.mode === 'find' && (operations.value.length || unavailable.value.length)) return ''
if (props.mode === 'run' && !resultEmpty.value) return ''
return props.output.trim() || t('agentStream.operations.failed')
})
function riskLabel(risk: string) {
const key = `agentStream.operations.risk.${risk}`
return te(key) ? t(key) : risk
}
</script>
<style lang="less" scoped>
.catalog-result { min-width: 0; font-size: var(--app-text-sm); color: var(--td-text-color-primary); }
.catalog-summary {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 4px 10px;
margin-bottom: 8px;
color: var(--td-text-color-secondary);
}
.catalog-operation-name { font-weight: 600; color: var(--td-text-color-primary); }
.catalog-empty { margin: 0; color: var(--td-text-color-placeholder); }
.catalog-list {
border: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-md);
overflow: hidden;
background: var(--td-bg-color-container);
max-height: 360px;
overflow-y: auto;
}
.catalog-item + .catalog-item { border-top: 1px solid var(--td-component-stroke); }
.catalog-item__head {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
margin: 0;
padding: 8px 10px;
border: 0;
background: transparent;
font: inherit;
color: inherit;
text-align: left;
}
.catalog-item__index {
flex-shrink: 0;
min-width: 22px;
font-size: var(--app-text-xs);
font-weight: 600;
color: var(--td-text-color-placeholder);
}
.catalog-item__name {
flex-shrink: 0;
max-width: 46%;
font-size: var(--app-text-sm);
line-height: 1.5;
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.catalog-item__summary {
flex: 1;
min-width: 0;
color: var(--td-text-color-secondary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.catalog-item__body, .catalog-item__reason {
margin: 0;
padding: 0 10px 10px 40px;
color: var(--td-text-color-secondary);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.catalog-item__body p { margin: 0 0 8px; }
.catalog-risk {
flex-shrink: 0;
padding: 0 6px;
border-radius: var(--app-radius-xs);
font-size: var(--app-text-xs);
line-height: 1.6;
color: var(--td-text-color-secondary);
background: var(--td-bg-color-secondarycontainer);
}
.catalog-risk[data-risk='write'] { color: var(--td-warning-color); }
.catalog-risk[data-risk='destructive'] { color: var(--td-error-color); }
.catalog-params { border: 1px solid var(--td-component-stroke); border-radius: var(--app-radius-md); overflow: hidden; }
.catalog-params__label {
padding: 6px 12px;
font-size: var(--app-text-xs);
font-weight: 600;
color: var(--td-text-color-placeholder);
background: var(--td-bg-color-secondarycontainer);
}
.catalog-param { padding: 8px 12px; }
.catalog-param + .catalog-param { border-top: 1px solid var(--td-component-stroke); }
.catalog-param__title { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.catalog-param__title code { font-weight: 600; }
.catalog-param__title span, .catalog-param__meta { color: var(--td-text-color-secondary); }
.catalog-required { color: var(--td-brand-color); }
.catalog-param p { margin: 4px 0 0; }
.catalog-unavailable, .catalog-meta { margin-top: 12px; }
.catalog-error { display: flex; align-items: flex-start; gap: 8px; color: var(--td-error-color); }
.catalog-error pre, .catalog-result :deep(pre) { margin: 0; }
.catalog-error pre {
flex: 1;
min-width: 0;
padding: 0;
background: transparent;
font: inherit;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
</style>
@@ -0,0 +1,122 @@
<template>
<div class="plan-display">
<div v-if="data.steps && data.steps.length > 0" class="plan-steps">
<div v-for="(step, index) in data.steps" :key="step.id || index" class="step-item" :class="`status-${step.status}`">
<div class="step-checkbox" :class="{ 'checked': step.status === 'completed', 'in-progress': step.status === 'in_progress' }">
<svg v-if="step.status === 'completed'" width="16" height="16" viewBox="0 0 16 16" fill="none">
<rect x="2" y="2" width="12" height="12" rx="2" fill="currentColor" />
<path d="M5 8L7 10L11 6" stroke="#fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
</svg>
<svg v-else width="16" height="16" viewBox="0 0 16 16" fill="none">
<rect x="2" y="2" width="12" height="12" rx="2" stroke="currentColor" stroke-width="1.5" fill="none" />
</svg>
</div>
<span class="step-description" :class="{ 'completed': step.status === 'completed' }">
{{ step.description }}
<span v-if="step.status === 'in_progress'" class="sparkle">✨</span>
</span>
</div>
</div>
<div v-else class="no-steps">
{{ $t('chat.noPlanSteps') }}
</div>
</div>
</template>
<script setup lang="ts">
import type { PlanData } from '@/types/tool-results';
interface Props {
data: PlanData;
}
const props = defineProps<Props>();
</script>
<style lang="less" scoped>
.plan-display {
font-size: var(--app-text-sm);
color: var(--td-text-color-secondary);
background: transparent;
padding: 6px 0 6px 12px;
margin: 0;
border: none !important;
box-shadow: none !important;
outline: none;
}
.plan-steps {
display: flex;
flex-direction: column;
gap: 3px;
}
.step-item {
display: flex;
align-items: flex-start;
gap: 7px;
padding: 1px 0;
transition: all var(--app-motion-fast);
&:last-child {
margin-bottom: 0;
}
&.status-in_progress {
.step-description {
color: var(--td-text-color-primary);
font-weight: 500;
}
}
}
.step-checkbox {
width: 14px;
height: 14px;
flex-shrink: 0;
margin-top: 1px;
display: flex;
align-items: center;
justify-content: center;
color: var(--td-text-color-placeholder);
&.checked {
color: var(--embed-primary, var(--td-brand-color));
}
&.in-progress {
color: var(--embed-primary, var(--td-brand-color));
svg rect {
stroke-width: 2;
}
}
}
.step-description {
flex: 1;
color: var(--td-text-color-secondary);
line-height: 1.5;
font-size: var(--app-text-sm);
&.completed {
text-decoration: line-through;
color: var(--td-text-color-placeholder);
}
.sparkle {
margin-left: 3px;
font-size: var(--app-text-xs);
}
}
.no-steps {
padding: 12px;
text-align: center;
color: var(--td-text-color-placeholder);
font-style: italic;
font-size: var(--app-text-sm);
}
</style>
@@ -0,0 +1,132 @@
<template>
<div class="read-skill-result">
<p v-if="description" class="read-skill-desc">{{ description }}</p>
<div v-if="files.length" class="read-skill-files">
<div class="read-skill-heading">{{ $t('agentStream.skillFiles.heading') }}</div>
<div class="results-list">
<ResultRow
v-for="(item, index) in files"
:key="item.path || `${item.name}-${index}`"
:index="index + 1"
:title="item.path || item.name"
:meta="item.isScript ? $t('agentStream.skillFiles.script') : ''"
:popup-key="item.path || index"
:show-popup="false"
/>
</div>
</div>
<div v-if="body" class="read-skill-stream">
<div class="read-skill-stream-label">{{ bodyLabel }}</div>
<pre class="read-skill-stream-body">{{ body }}</pre>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { skillFileListItems } from '@/utils/skillToolDisplay'
import type { ReadSkillData } from '@/types/tool-results'
import ResultRow from './ResultRow.vue'
const props = defineProps<{
data: ReadSkillData | Record<string, unknown>
}>()
const { t } = useI18n()
const record = computed(() => (props.data || {}) as Record<string, unknown>)
const description = computed(() => {
const value = record.value.description
return typeof value === 'string' ? value.trim() : ''
})
const files = computed(() => skillFileListItems(record.value))
const filePath = computed(() => {
const value = record.value.file_path
return typeof value === 'string' ? value.trim() : ''
})
const body = computed(() => {
const content = record.value.content
if (typeof content === 'string' && content.trim()) return content
if (filePath.value) return ''
const instructions = record.value.instructions
return typeof instructions === 'string' ? instructions : ''
})
const bodyLabel = computed(() =>
filePath.value
? filePath.value
: t('agentStream.skillFiles.instructions'),
)
</script>
<style lang="less" scoped>
.read-skill-result {
display: flex;
flex-direction: column;
gap: 10px;
min-width: 0;
}
.read-skill-desc {
margin: 0;
font-size: var(--app-text-sm);
line-height: 1.55;
color: var(--td-text-color-secondary);
}
.read-skill-heading {
margin-bottom: 4px;
font-size: var(--app-text-sm);
font-weight: 500;
line-height: 1.4;
color: var(--td-text-color-secondary);
}
.read-skill-stream {
min-width: 0;
border: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-sm);
overflow: hidden;
background: var(--td-bg-color-container);
}
.read-skill-stream-label {
padding: 6px 12px;
font-size: var(--app-text-sm);
font-weight: 500;
line-height: 1.4;
color: var(--td-text-color-secondary);
background: var(--td-bg-color-secondarycontainer);
border-bottom: 1px solid var(--td-component-stroke);
}
.read-skill-stream-body {
margin: 0;
padding: 10px 12px;
max-height: 280px;
overflow: auto;
font-family: var(--app-font-family-mono);
font-size: var(--app-text-sm);
line-height: 1.55;
color: var(--td-text-color-primary);
white-space: pre-wrap;
word-break: break-word;
&::-webkit-scrollbar {
width: 8px;
height: 8px;
}
&::-webkit-scrollbar-thumb {
background: var(--td-component-border);
border-radius: var(--app-radius-xs);
}
}
</style>
@@ -0,0 +1,154 @@
<template>
<div class="related-chunks">
<div v-if="data.chunks && data.chunks.length > 0" class="chunks-list">
<div
v-for="chunk in data.chunks"
:key="chunk.chunk_id"
class="result-item"
>
<t-popup
:overlayClassName="`chunk-popup-${chunk.chunk_id}`"
placement="bottom-left"
width="400"
:showArrow="false"
trigger="click"
destroy-on-close
>
<template #content>
<ContentPopup
:content="chunk.content"
:chunk-id="chunk.chunk_id"
/>
</template>
<div class="result-header">
<div class="result-title">
<span class="chunk-index">{{ $t('chat.chunkIndexLabel', { index: chunk.index }) }}</span>
<span class="chunk-position">{{ $t('chat.chunkPositionLabel', { position: chunk.chunk_index }) }}</span>
</div>
</div>
</t-popup>
</div>
</div>
<div v-else class="empty-state">
{{ $t('chat.noRelatedChunks') }}
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed } from 'vue';
import type { RelatedChunksData } from '@/types/tool-results';
import ContentPopup from './ContentPopup.vue';
const props = defineProps<{
data: RelatedChunksData;
}>();
</script>
<style lang="less" scoped>
@import './tool-results.less';
.related-chunks {
display: flex;
flex-direction: column;
gap: 8px;
padding: 0 0 0 12px;
.info-section {
margin-bottom: 8px;
padding: 0;
.info-field {
font-size: var(--app-text-xs);
margin-bottom: 4px;
.field-label {
font-size: var(--app-text-xs);
color: var(--td-text-color-placeholder);
min-width: 70px;
}
.field-value {
font-size: var(--app-text-xs);
color: var(--td-text-color-secondary);
}
}
}
}
.chunks-list {
display: flex;
flex-direction: column;
gap: 4px;
}
.result-item {
background: transparent;
border: none;
border-radius: 0;
overflow: visible;
}
.result-header {
padding: 4px 0;
cursor: pointer;
user-select: none;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
transition: color 0.25s cubic-bezier(0.4, 0, 0.2, 1);
&:hover {
color: var(--td-brand-color);
}
}
.result-title {
display: flex;
align-items: center;
gap: 6px;
flex: 1;
min-width: 0;
font-size: var(--app-text-sm);
}
.chunk-index {
font-size: var(--app-text-sm);
color: var(--td-text-color-primary);
font-weight: 600;
flex-shrink: 0;
}
.chunk-position {
font-size: var(--app-text-xs);
color: var(--td-text-color-placeholder);
}
// Popup overlay styles
:deep([class*="chunk-popup-"]) {
.t-popup__content {
max-height: 400px;
max-width: 500px;
overflow-y: auto;
overflow-x: hidden;
padding: 0;
border-radius: var(--app-radius-sm);
box-shadow: var(--td-shadow-3);
word-wrap: break-word;
word-break: break-word;
}
}
code {
font-family: var(--app-font-family-mono);
font-size: var(--app-text-xs);
background: var(--td-bg-color-secondarycontainer);
padding: 2px 4px;
border-radius: 3px;
}
</style>
@@ -0,0 +1,137 @@
<template>
<div class="result-row" :class="{ 'result-row--has-preview': showPopup }">
<span class="result-row__index">#{{ index }}</span>
<span class="result-row__title" :title="title">{{ title }}</span>
<span v-if="meta" class="result-row__meta">{{ meta }}</span>
<t-popup
v-if="showPopup"
:overlayClassName="`tool-result-popup tool-result-popup-${popupKey}`"
placement="bottom-left"
:width="400"
:showArrow="false"
trigger="hover"
destroy-on-close
>
<template #content>
<ContentPopup
:content="content"
:chunks="chunks"
:chunk-id="chunkId"
:knowledge-id="knowledgeId"
:highlight="highlight"
:regex="regex"
/>
</template>
<span class="result-row__preview" :aria-label="$t('chat.previewContent')">
<browse-icon />
</span>
</t-popup>
</div>
</template>
<script setup lang="ts">
import { BrowseIcon } from 'tdesign-icons-vue-next';
import ContentPopup from './ContentPopup.vue';
interface ChunkContent {
content: string;
chunk_id?: string;
knowledge_id?: string;
}
withDefaults(
defineProps<{
index: number;
title: string;
meta?: string;
popupKey: string | number;
showPopup?: boolean;
content?: string;
chunks?: ChunkContent[];
chunkId?: string;
knowledgeId?: string;
highlight?: string;
regex?: boolean;
}>(),
{ showPopup: true },
);
</script>
<style lang="less" scoped>
.result-row {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
padding: 4px 8px;
border-radius: var(--app-radius-xs);
font-size: var(--app-text-sm);
line-height: 1.4;
user-select: none;
&--has-preview:hover {
background: var(--td-bg-color-secondarycontainer);
.result-row__preview {
opacity: 1;
}
}
}
.result-row__preview {
flex-shrink: 0;
display: inline-flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
border-radius: var(--app-radius-xs);
font-size: var(--app-text-base);
color: var(--td-text-color-placeholder);
cursor: pointer;
opacity: 0.5;
transition: opacity var(--app-motion-fast) ease, color var(--app-motion-fast) ease, background var(--app-motion-fast) ease;
&:hover {
opacity: 1;
color: var(--td-brand-color);
background: var(--td-bg-color-container);
}
}
.result-row__index {
flex-shrink: 0;
min-width: 22px;
font-size: var(--app-text-xs);
font-weight: 600;
color: var(--td-text-color-placeholder);
}
.result-row__title {
flex: 1;
min-width: 0;
font-weight: 500;
color: var(--td-text-color-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.result-row__meta {
flex-shrink: 0;
font-size: var(--app-text-xs);
font-weight: 400;
color: var(--td-text-color-placeholder);
}
</style>
<!-- Non-scoped: the popup overlay is teleported to <body>, so style it globally. -->
<style lang="less">
.tool-result-popup .t-popup__content {
padding: 0;
background: transparent;
border: none;
box-shadow: none;
}
</style>
@@ -0,0 +1,89 @@
<template>
<div class="sandbox-files-result">
<div v-if="summary" class="results-summary-text">{{ summary }}</div>
<div v-if="items.length" class="results-list">
<ResultRow
v-for="(item, index) in items"
:key="item.path || `${item.name}-${index}`"
:index="index + 1"
:title="item.name || item.path"
:meta="metaFor(item)"
:popup-key="item.path || index"
:show-popup="false"
/>
</div>
<div v-else class="empty-state">{{ $t('agentStream.sandboxFiles.empty') }}</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { formatFileSize } from '@/utils/files'
import {
formatSandboxModifiedAt,
sandboxFileListItems,
type SkillFileListItem,
} from '@/utils/skillToolDisplay'
import type { ListSandboxFilesData } from '@/types/tool-results'
import ResultRow from './ResultRow.vue'
const props = defineProps<{
data: ListSandboxFilesData | Record<string, unknown>
}>()
const { t } = useI18n()
const items = computed(() => sandboxFileListItems(props.data))
const summary = computed(() => {
if (!items.value.length) return ''
const record = (props.data || {}) as Record<string, unknown>
const count = typeof record.count === 'number' ? record.count : items.value.length
const parts = [t('agentStream.sandboxFiles.found', { count })]
if (record.truncated) {
parts.push(t('agentStream.sandboxFiles.truncated'))
}
return parts.join(' · ')
})
function sizeLabel(size?: number): string {
if (size == null || !Number.isFinite(size) || size < 0) return ''
if (size === 0) return '0 B'
return formatFileSize(size)
}
function metaFor(item: SkillFileListItem): string {
const parts = [sizeLabel(item.size), item.modifiedAt ? formatSandboxModifiedAt(item.modifiedAt) : '']
return parts.filter(Boolean).join(' · ')
}
</script>
<style lang="less" scoped>
@import './tool-results.less';
.sandbox-files-result {
display: flex;
flex-direction: column;
gap: 8px;
}
.results-summary-text {
font-size: var(--agent-step-summary-size, 12px);
font-weight: 400;
color: var(--td-text-color-secondary);
line-height: 1.5;
}
.results-list {
display: flex;
flex-direction: column;
min-width: 0;
}
.empty-state {
font-size: var(--app-text-sm);
line-height: 1.5;
color: var(--td-text-color-placeholder);
}
</style>
@@ -0,0 +1,174 @@
<template>
<div class="search-results">
<!-- Search Results List (chunks merged per document) -->
<div v-if="groupedResults.length > 0" class="results-list">
<ResultRow
v-for="(group, idx) in groupedResults"
:key="group.key"
:index="idx + 1"
:title="group.title"
:meta="$t('agentStream.grepResults.chunkHits', { count: group.chunks.length })"
:popup-key="group.knowledge_id"
:chunks="group.chunks"
:chunk-id="group.chunks.length === 1 ? group.chunks[0].chunk_id : undefined"
:knowledge-id="group.knowledge_id"
:highlight="highlightQuery"
/>
</div>
<!-- Empty State -->
<div v-else class="empty-state">
{{ $t('chat.noSearchResults') }}
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import type { SearchResultsData, SearchResultItem, RelevanceLevel } from '@/types/tool-results';
import { getMatchTypeIcon } from '@/utils/tool-icons';
import ResultRow from './ResultRow.vue';
import { useI18n } from 'vue-i18n';
const props = defineProps<{
data: SearchResultsData;
arguments?: Record<string, any> | string;
}>();
const { t } = useI18n();
const results = computed(() => props.data.results || []);
const kbCounts = computed(() => props.data.kb_counts);
interface GroupedResult {
key: string;
knowledge_id: string;
title: string;
chunks: { content: string; chunk_id: string; knowledge_id: string }[];
}
// Hybrid retrieval can return several chunks from the same document; collapse
// them into one row so the same file is not listed repeatedly. FAQ entries are
// the exception: they all share the owning document's title, so each entry is
// kept as its own row labelled by its standard question to stay distinguishable.
const groupedResults = computed<GroupedResult[]>(() => {
const map = new Map<string, GroupedResult>();
const order: string[] = [];
for (const r of results.value) {
const faqQuestion = r.faq_standard_question?.trim();
const isFaq = !!faqQuestion;
const key = isFaq ? r.chunk_id : r.knowledge_id || r.chunk_id;
if (!map.has(key)) {
map.set(key, {
key,
knowledge_id: r.knowledge_id,
title: (isFaq ? faqQuestion : r.knowledge_title) || r.knowledge_title,
chunks: [],
});
order.push(key);
}
map.get(key)!.chunks.push({
content: r.content,
chunk_id: r.chunk_id,
knowledge_id: r.knowledge_id,
});
}
return order.map((k) => map.get(k)!);
});
// Parse arguments if it's a string
const parsedArguments = computed(() => {
const args = props.arguments;
if (!args) return null;
// If it's already an object, return it
if (typeof args === 'object' && !Array.isArray(args)) {
return args;
}
// If it's a string, try to parse it
if (typeof args === 'string') {
try {
return JSON.parse(args);
} catch (e) {
console.warn('Failed to parse arguments:', e);
return null;
}
}
return null;
});
// Highlight terms for the content popup: the natural-language query plus any
// explicit sub-queries passed to the search tool.
const highlightQuery = computed(() => {
const parts: string[] = [];
const args = parsedArguments.value;
if (args && typeof args === 'object') {
if (typeof args.query === 'string') parts.push(args.query);
if (Array.isArray(args.queries)) {
parts.push(...args.queries.filter((q: unknown): q is string => typeof q === 'string'));
}
}
if (parts.length === 0 && props.data.query) parts.push(props.data.query);
return parts.join(' ');
});
// Check if there are search parameters to display (excluding query parameters which are in title)
const hasSearchParams = computed(() => {
const args = parsedArguments.value;
if (!args || typeof args !== 'object') return false;
return !!(
(Array.isArray(args.knowledge_base_ids) && args.knowledge_base_ids.length > 0) ||
args.top_k || args.vector_threshold || args.keyword_threshold || args.min_score);
});
const hasOtherParams = computed(() => {
const args = parsedArguments.value;
if (!args || typeof args !== 'object') return false;
return !!(args.top_k || args.vector_threshold || args.keyword_threshold || args.min_score);
});
const getRelevanceClass = (level: RelevanceLevel): string => {
const classMap: Record<RelevanceLevel, string> = {
'High Relevance': 'high',
'Medium Relevance': 'medium',
'Low Relevance': 'low',
'Weak Relevance': 'weak',
};
return classMap[level] || 'weak';
};
const getRelevanceLabel = (level: RelevanceLevel): string => {
const labelMap: Record<RelevanceLevel, string> = {
'High Relevance': t('chat.relevanceHigh'),
'Medium Relevance': t('chat.relevanceMedium'),
'Low Relevance': t('chat.relevanceLow'),
'Weak Relevance': t('chat.relevanceWeak'),
};
return labelMap[level] || level;
};
</script>
<style lang="less" scoped>
@import './tool-results.less';
.search-results {
display: flex;
flex-direction: column;
padding: 0 0 0 12px;
gap: 3px;
}
.results-list {
display: flex;
flex-direction: column;
gap: 3px;
max-height: 200px;
overflow-y: auto;
}
</style>
@@ -0,0 +1,199 @@
<template>
<div class="shell-exec-result">
<div v-if="view.command" class="shell-exec-command">
<span class="shell-exec-prompt" aria-hidden="true">$</span>
<pre class="shell-exec-command-text">{{ view.command }}</pre>
</div>
<div v-if="hasMeta" class="shell-exec-meta">
<span v-if="view.workDir">{{ $t('agentStream.shellExec.workDir') }} {{ view.workDir }}</span>
<span v-if="view.exitCode !== null" :class="{ 'is-error': view.exitCode !== 0 }">
{{ $t('agentStream.shellExec.exitCode') }} {{ view.exitCode }}
</span>
<span v-if="durationLabel">{{ durationLabel }}</span>
<span v-if="view.killed">{{ $t('agentStream.shellExec.killed') }}</span>
<span v-if="view.truncated">{{ $t('agentStream.shellExec.truncated') }}</span>
<span v-if="workId">{{ workId }}</span>
<span v-if="workState">{{ workState }}</span>
</div>
<div v-if="note" class="shell-exec-note">{{ note }}</div>
<div v-if="view.stdoutBinary || view.stderrBinary" class="shell-exec-note">
{{ $t('agentStream.shellExec.binarySuppressed') }}
</div>
<div v-if="view.stdout" class="shell-exec-stream">
<div class="shell-exec-stream-label">{{ $t('agentStream.shellExec.stdout') }}</div>
<pre class="shell-exec-stream-body">{{ view.stdout }}</pre>
</div>
<div v-if="view.stderr" class="shell-exec-stream is-stderr">
<div class="shell-exec-stream-label">{{ $t('agentStream.shellExec.stderr') }}</div>
<pre class="shell-exec-stream-body">{{ view.stderr }}</pre>
</div>
<div v-if="!view.stdout && !view.stderr && !view.stdoutBinary && !view.stderrBinary" class="shell-exec-empty">
{{ $t('agentStream.shellExec.emptyOutput') }}
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import type { ShellJobPayload } from '@/api/chat/background-work'
import type { ShellExecData } from '@/types/tool-results'
import { buildShellExecView } from '@/utils/shellExecResult'
const props = defineProps<{
data?: ShellExecData | ShellJobPayload | Record<string, unknown> | null
output?: string
arguments?: Record<string, unknown>
}>()
const source = computed(() => {
const value = props.data
if (value && typeof value === 'object') return value as unknown as Record<string, unknown>
return null
})
const view = computed(() =>
buildShellExecView(source.value, props.arguments, props.output),
)
function textField(key: string): string {
const value = source.value?.[key]
return typeof value === 'string' ? value : ''
}
const workId = computed(() => textField('work_id'))
const workState = computed(() => textField('state'))
const note = computed(() => textField('note'))
const hasMeta = computed(() =>
Boolean(
view.value.workDir ||
view.value.exitCode !== null ||
view.value.durationMs !== null ||
view.value.killed ||
view.value.truncated ||
workId.value ||
workState.value,
),
)
const durationLabel = computed(() => {
const ms = view.value.durationMs
if (ms == null) return ''
if (ms < 1000) return `${Math.round(ms)}ms`
const seconds = ms / 1000
if (seconds < 10) return `${seconds.toFixed(1)}s`
return `${Math.round(seconds)}s`
})
</script>
<style lang="less" scoped>
.shell-exec-result {
display: flex;
flex-direction: column;
gap: 8px;
min-width: 0;
}
.shell-exec-command {
display: flex;
align-items: flex-start;
gap: 8px;
padding: 10px 12px;
border: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-sm);
background: var(--td-bg-color-secondarycontainer);
}
.shell-exec-prompt {
flex-shrink: 0;
margin-top: 1px;
font-family: var(--app-font-family-mono);
font-size: var(--app-text-sm);
font-weight: 600;
line-height: 1.55;
color: var(--td-text-color-placeholder);
}
.shell-exec-command-text {
flex: 1;
min-width: 0;
margin: 0;
font-family: var(--app-font-family-mono);
font-size: var(--app-text-sm);
line-height: 1.55;
color: var(--td-text-color-primary);
white-space: pre-wrap;
word-break: break-word;
}
.shell-exec-meta {
display: flex;
flex-wrap: wrap;
gap: 4px 12px;
font-size: var(--app-text-sm);
line-height: 1.4;
color: var(--td-text-color-placeholder);
.is-error {
color: var(--td-error-color);
}
}
.shell-exec-note,
.shell-exec-empty {
font-size: var(--app-text-sm);
line-height: 1.4;
color: var(--td-text-color-placeholder);
}
.shell-exec-stream {
min-width: 0;
border: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-sm);
overflow: hidden;
background: var(--td-bg-color-container);
&.is-stderr .shell-exec-stream-label {
color: var(--td-error-color);
}
}
.shell-exec-stream-label {
padding: 6px 12px;
font-size: var(--app-text-sm);
font-weight: 500;
line-height: 1.4;
color: var(--td-text-color-secondary);
background: var(--td-bg-color-secondarycontainer);
border-bottom: 1px solid var(--td-component-stroke);
}
.shell-exec-stream-body {
margin: 0;
padding: 10px 12px;
max-height: 280px;
overflow: auto;
font-family: var(--app-font-family-mono);
font-size: var(--app-text-sm);
line-height: 1.55;
color: var(--td-text-color-primary);
white-space: pre-wrap;
word-break: break-word;
&::-webkit-scrollbar {
width: 8px;
height: 8px;
}
&::-webkit-scrollbar-thumb {
background: var(--td-component-border);
border-radius: var(--app-radius-xs);
}
}
</style>
@@ -0,0 +1,52 @@
<template>
<div class="thinking-display">
<div class="thinking-content">
<div class="thinking-icon" aria-hidden="true">💭</div>
<div class="thinking-text">{{ data.thought }}</div>
</div>
</div>
</template>
<script setup lang="ts">
import type { ThinkingData } from '@/types/tool-results';
import { useI18n } from 'vue-i18n';
const props = defineProps<{
data: ThinkingData;
}>();
useI18n(); // ensure component reacts to locale changes if needed
</script>
<style lang="less" scoped>
@import './tool-results.less';
.thinking-display {
padding: 0;
}
.thinking-content {
display: flex;
gap: 10px;
padding: 12px 14px;
background: var(--td-bg-color-secondarycontainer);
border-radius: var(--app-radius-sm);
border-left: 3px solid var(--td-text-color-placeholder);
}
.thinking-icon {
font-size: var(--app-text-xl);
flex-shrink: 0;
line-height: 1.5;
}
.thinking-text {
font-size: var(--app-text-lg);
color: var(--td-text-color-primary);
line-height: 1.65;
white-space: pre-wrap;
word-break: break-word;
flex: 1;
font-weight: 400;
}
</style>
@@ -0,0 +1,176 @@
<template>
<div class="doc-result">
<div v-if="plainError" class="doc-error" role="alert">
<t-icon name="error-circle" />
<pre>{{ plainError }}</pre>
</div>
<template v-else-if="mode === 'search'">
<div class="doc-summary">
{{ listingPages
? $t('agentStream.weknoraDocs.pages', { count: pages.length })
: $t('agentStream.weknoraDocs.hits', { count: hits.length }) }}
</div>
<p v-if="!rows.length" class="doc-empty">{{ $t('agentStream.weknoraDocs.empty') }}</p>
<div v-else class="doc-list">
<article v-for="(row, index) in rows" :key="`${row.path}-${index}`" class="doc-item">
<div class="doc-item__head">
<span class="doc-item__index">#{{ index + 1 }}</span>
<a
v-if="row.href"
class="doc-item__title"
:href="row.href"
target="_blank"
rel="noopener noreferrer"
>{{ row.title }}</a>
<span v-else class="doc-item__title">{{ row.title }}</span>
<span v-if="row.category" class="doc-item__meta">{{ row.category }}</span>
</div>
<p v-if="row.snippet" class="doc-item__snippet">{{ row.snippet }}</p>
<p v-if="row.locator" class="doc-item__path">{{ row.locator }}</p>
</article>
</div>
</template>
<template v-else>
<div v-if="read.error" class="doc-error" role="alert">
<t-icon name="error-circle" />
<pre>{{ read.error }}</pre>
</div>
<div v-if="read.title || read.url" class="doc-read__head">
<span v-if="read.title" class="doc-read__title">{{ read.title }}</span>
<a v-if="readHref" class="doc-read__link" :href="readHref" target="_blank" rel="noopener noreferrer">
{{ $t('agentStream.weknoraDocs.openDoc') }}
</a>
</div>
<p v-if="read.section" class="doc-read__section">{{ read.section }}</p>
<div v-if="read.outline.length" class="doc-outline">
<div class="doc-summary">{{ $t('agentStream.weknoraDocs.outline') }}</div>
<ul>
<li
v-for="(entry, index) in read.outline"
:key="`${entry.anchor}-${index}`"
:style="{ paddingLeft: `${Math.max(0, entry.level - 2) * 12}px` }"
>{{ entry.heading }}</li>
</ul>
</div>
<div v-if="read.content" class="doc-read__content">
<div class="doc-summary">{{ $t('agentStream.weknoraDocs.content') }}</div>
<DocMarkdown :source="read.content" />
<p v-if="read.truncated" class="doc-note">{{ $t('agentStream.weknoraDocs.truncated') }}</p>
</div>
<p v-else-if="!read.outline.length && !read.error" class="doc-empty">{{ $t('agentStream.weknoraDocs.empty') }}</p>
</template>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import {
docHits,
docPages,
docReadView,
parseCatalogPayload,
safeDocUrl,
} from '@/utils/catalogToolDisplay'
import DocMarkdown from './DocMarkdown.vue'
const props = withDefaults(defineProps<{
mode: 'search' | 'read'
output?: string
data?: Record<string, unknown>
success?: boolean
}>(), { output: '', success: undefined })
const { t } = useI18n()
const payload = computed(() => parseCatalogPayload(props.output, props.data))
const pages = computed(() => docPages(payload.value))
const hits = computed(() => docHits(payload.value))
const read = computed(() => docReadView(payload.value))
const readHref = computed(() => safeDocUrl(read.value.url))
const listingPages = computed(() => Array.isArray(payload.value.pages))
const rows = computed(() => {
const source = listingPages.value
? pages.value.map((page) => ({ ...page, anchor: '', snippet: '' }))
: hits.value
return source.map((row) => ({
...row,
href: safeDocUrl(row.url),
locator: row.anchor ? `${row.path}#${row.anchor}` : row.path,
}))
})
const structured = computed(() => (
props.mode === 'search'
? Array.isArray(payload.value.pages) || Array.isArray(payload.value.results)
: Boolean(read.value.title || read.value.path || read.value.content || read.value.outline.length || read.value.error)
))
const plainError = computed(() => {
if (props.success !== false || structured.value) return ''
return props.output.trim() || t('agentStream.weknoraDocs.failed')
})
</script>
<style lang="less" scoped>
.doc-result { min-width: 0; font-size: var(--app-text-sm); color: var(--td-text-color-primary); }
.doc-summary { margin-bottom: 8px; color: var(--td-text-color-secondary); }
.doc-empty, .doc-note { margin: 0; color: var(--td-text-color-placeholder); }
.doc-note { margin-top: 8px; }
.doc-list {
border: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-md);
overflow: hidden;
background: var(--td-bg-color-container);
max-height: 360px;
overflow-y: auto;
}
.doc-item + .doc-item { border-top: 1px solid var(--td-component-stroke); }
.doc-item { padding: 8px 10px; }
.doc-item__head { display: flex; align-items: baseline; gap: 8px; min-width: 0; }
.doc-item__index {
flex-shrink: 0;
min-width: 22px;
font-size: var(--app-text-xs);
font-weight: 600;
color: var(--td-text-color-placeholder);
}
.doc-item__title {
flex: 1;
min-width: 0;
font-weight: 600;
color: var(--td-text-color-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
a.doc-item__title { color: var(--td-brand-color); text-decoration: none; }
a.doc-item__title:hover { text-decoration: underline; }
.doc-item__meta, .doc-item__path { flex-shrink: 0; font-size: var(--app-text-xs); color: var(--td-text-color-placeholder); }
.doc-item__snippet, .doc-item__path { margin: 4px 0 0 30px; }
.doc-item__snippet {
color: var(--td-text-color-secondary);
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
overflow-wrap: anywhere;
}
.doc-read__head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 8px 12px; margin-bottom: 6px; }
.doc-read__title { font-weight: 600; }
.doc-read__link { color: var(--td-brand-color); }
.doc-read__section { margin: 0 0 8px; color: var(--td-text-color-secondary); }
.doc-outline ul { margin: 0; padding: 0; list-style: none; max-height: 220px; overflow: auto; }
.doc-outline li { padding: 2px 0; color: var(--td-text-color-secondary); }
.doc-read__content { margin-top: 8px; }
.doc-error { display: flex; align-items: flex-start; gap: 8px; margin-bottom: 8px; color: var(--td-error-color); }
.doc-error pre {
flex: 1;
min-width: 0;
margin: 0;
padding: 0;
background: transparent;
font: inherit;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
</style>
@@ -0,0 +1,348 @@
<template>
<div class="web-fetch-results">
<div v-if="items.length > 0" class="results-list">
<div
v-for="(item, index) in items"
:key="indexKey(index, item)"
class="result-card"
>
<div class="result-header" @click="toggleCard(index)">
<div class="result-title">
<span class="result-index">#{{ index + 1 }}</span>
<a
v-if="item.url"
:href="item.url"
class="result-link"
target="_blank"
rel="noopener noreferrer"
@click.stop
>
<span class="result-domain">{{ safeHostname(item.url) }}</span>
</a>
<span v-else class="result-domain">{{ $t('chat.unknownLink') }}</span>
</div>
<div class="result-meta">
<span
v-if="itemStatus(item)"
class="meta-pill"
:class="statusClass(item)"
>{{ statusLabel(item) }}</span>
<span v-if="item.method" class="meta-pill method">{{ formatMethod(item.method) }}</span>
<span v-if="item.content_length" class="meta-text">{{ $t('chat.contentLengthLabel', { value: formatLength(item.content_length) }) }}</span>
<t-icon
:name="isExpanded(index) ? 'chevron-up' : 'chevron-down'"
class="expand-icon"
/>
</div>
</div>
<div class="result-content" :class="{ expanded: isExpanded(index) }">
<div class="info-section">
<div class="info-field">
<span class="field-label">URL</span>
<span class="field-value">
<a
v-if="item.url"
:href="item.url"
target="_blank"
rel="noopener noreferrer"
>{{ item.url }}</a>
<span v-else>{{ $t('chat.notProvided') }}</span>
</span>
</div>
</div>
<div v-if="itemError(item)" class="info-section">
<div class="info-section-title error">{{ $t('chat.errorMessageLabel') }}</div>
<div v-if="item.error_code" class="info-field">
<span class="field-label">{{ $t('chat.webFetchErrorCode') }}</span>
<span class="field-value">{{ item.error_code }}</span>
</div>
<div v-if="item.retryable !== undefined" class="info-field">
<span class="field-label">{{ $t('chat.webFetchRetryable') }}</span>
<span class="field-value">{{ item.retryable ? $t('common.yes') : $t('common.no') }}</span>
</div>
<div class="full-content error-text">{{ itemError(item) }}</div>
</div>
<div v-else-if="isSuccessItem(item)">
<div v-if="item.summary" class="info-section">
<div class="info-section-title">{{ $t('chat.summaryLabel') }}</div>
<div class="full-content">{{ item.summary }}</div>
</div>
<div v-else-if="item.summary_status === 'failed'" class="info-section">
<div class="info-section-title error">{{ $t('chat.webFetchSummaryFailed') }}</div>
<div v-if="item.summary_error_code" class="info-field">
<span class="field-label">{{ $t('chat.webFetchErrorCode') }}</span>
<span class="field-value">{{ item.summary_error_code }}</span>
</div>
<div v-if="item.summary_error_message" class="full-content error-text">
{{ item.summary_error_message }}
</div>
</div>
<div v-if="item.raw_content" class="info-section">
<div class="info-section-title">
{{ $t('chat.rawTextLabel') }}
<span class="raw-length" v-if="item.content_length">
({{ formatLength(item.content_length) }})
</span>
</div>
<div v-if="item.offset !== undefined" class="info-field">
{{ $t('chat.webFetchContentRange', { start: item.offset, end: item.offset + (item.returned_chars ?? 0), total: item.content_length }) }}
<span v-if="item.truncated"> · {{ $t('chat.webFetchPartialContent') }}</span>
</div>
<div v-if="isRawExpanded(index)" class="full-content">
{{ item.raw_content }}
</div>
<div v-else class="content-preview">
{{ truncate(item.raw_content) }}
</div>
<button class="action-button" @click.stop="toggleRaw(index)">
{{ isRawExpanded(index) ? $t('chat.collapseRaw') : $t('chat.expandRaw') }}
</button>
</div>
</div>
</div>
</div>
</div>
<div v-else class="empty-state">{{ $t('chat.noWebContent') }}</div>
</div>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import type { WebFetchResultsData, WebFetchResultItem } from '@/types/tool-results';
import { useI18n } from 'vue-i18n';
interface Props {
data: WebFetchResultsData;
}
const props = defineProps<Props>();
const { t } = useI18n();
const items = computed<WebFetchResultItem[]>(() => props.data.results || []);
const expandedCards = ref<Set<number>>(new Set());
const expandedRaw = ref<Record<number, boolean>>({});
watch(
items,
(list) => {
const set = new Set<number>();
list.forEach((_item, idx) => {
set.add(idx);
});
expandedCards.value = set;
expandedRaw.value = {};
},
{ immediate: true }
);
const itemStatus = (item: WebFetchResultItem): string | undefined => item.status;
const isSuccessItem = (item: WebFetchResultItem): boolean => {
return !item.status || item.status === 'success';
};
const itemError = (item: WebFetchResultItem): string => {
return item.error_message || item.error || '';
};
const statusLabel = (item: WebFetchResultItem): string => {
switch (item.status) {
case 'failed':
return t('chat.webFetchStatusFailed');
case 'skipped':
return t('chat.webFetchStatusSkipped');
case 'success':
return t('chat.webFetchStatusSuccess');
default:
return t('chat.webFetchStatusSuccess');
}
};
const statusClass = (item: WebFetchResultItem): string => {
switch (item.status) {
case 'failed':
return 'status-failed';
case 'skipped':
return 'status-skipped';
default:
return 'status-success';
}
};
const toggleCard = (index: number) => {
if (expandedCards.value.has(index)) {
expandedCards.value.delete(index);
} else {
expandedCards.value.add(index);
}
};
const isExpanded = (index: number): boolean => expandedCards.value.has(index);
const toggleRaw = (index: number) => {
expandedRaw.value[index] = !expandedRaw.value[index];
};
const isRawExpanded = (index: number): boolean => !!expandedRaw.value[index];
const truncate = (content: string, maxLength = 480): string => {
if (!content) return '';
if (content.length <= maxLength) return content;
return `${content.substring(0, maxLength)}…`;
};
const safeHostname = (url: string): string => {
try {
const urlObj = new URL(url);
return urlObj.hostname;
} catch {
return url;
}
};
const formatLength = (length: number): string => {
if (!length || Number.isNaN(length)) return t('chat.lengthChars', { value: 0 });
if (length >= 10000) {
return t('chat.lengthTenThousands', { value: (length / 10000).toFixed(1) });
}
if (length >= 1000) {
return t('chat.lengthThousands', { value: (length / 1000).toFixed(1) });
}
return t('chat.lengthChars', { value: length });
};
const formatMethod = (method: string): string => {
if (!method) return '';
if (method.toLowerCase() === 'chromedp') {
return 'Chromedp';
}
if (method.toLowerCase() === 'http') {
return 'HTTP';
}
return method;
};
const indexKey = (index: number, item: WebFetchResultItem): string => {
return `${index}-${item.url || 'unknown'}`;
};
</script>
<style lang="less" scoped>
@import './tool-results.less';
.web-fetch-results {
display: flex;
flex-direction: column;
gap: 6px;
padding: 6px 6px 0 6px;
}
.results-list {
display: flex;
flex-direction: column;
gap: 6px;
}
.result-index {
font-size: var(--app-text-xs);
font-weight: 600;
color: var(--td-text-color-placeholder);
}
.result-link {
display: inline-flex;
align-items: center;
gap: 4px;
color: var(--td-text-color-primary);
font-size: var(--app-text-sm);
font-weight: 500;
text-decoration: none;
transition: color var(--app-motion-fast) ease;
&:hover {
color: var(--td-brand-color);
text-decoration: underline;
}
}
.result-domain {
font-size: var(--app-text-sm);
font-weight: 500;
color: var(--td-text-color-primary);
}
.meta-pill {
display: inline-flex;
align-items: center;
padding: 2px 6px;
border-radius: var(--app-radius-pill);
font-size: var(--app-text-2xs);
font-weight: 600;
line-height: 1.4;
&.status-success {
background: color-mix(in srgb, var(--td-brand-color) 8%, transparent);
color: var(--td-success-color);
}
&.status-failed {
background: var(--td-error-color-light);
color: var(--td-error-color);
}
&.status-skipped {
background: rgba(0, 0, 0, 0.06);
color: var(--td-text-color-secondary);
}
&.method {
background: color-mix(in srgb, var(--td-brand-color) 8%, transparent);
color: var(--td-success-color);
}
}
.meta-text {
font-size: var(--app-text-xs);
color: var(--td-text-color-secondary);
}
.result-content.expanded {
padding-top: 10px;
}
.info-field .field-value a {
color: var(--td-brand-color);
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
.raw-length {
font-size: var(--app-text-xs);
color: var(--td-text-color-placeholder);
margin-left: 4px;
font-weight: normal;
}
.action-button {
margin-top: 6px;
}
.info-section-title.error {
color: var(--td-error-color);
}
.full-content.error-text {
background: var(--td-error-color-light);
border-color: var(--td-error-color-focus);
color: var(--td-error-color);
}
</style>
@@ -0,0 +1,314 @@
<template>
<div class="web-search-results">
<!-- Grouped Results List -->
<div v-if="groupedResults && groupedResults.length > 0" class="results-groups">
<div
v-for="group in groupedResults"
:key="group.key"
class="results-group"
>
<!-- <div class="group-header">
<span class="group-intro">{{ $t('chat.webGroupIntro', { count: group.items.length }) }}</span>
<span class="group-source">{{ group.label }}</span>
</div> -->
<div class="results-list">
<div
v-for="result in group.items"
:key="result.result_index"
class="result-item"
>
<div class="result-header">
<div class="result-index">#{{ result.result_index }}</div>
<a
v-if="result.url"
:href="result.url"
:title="result.url"
target="_blank"
rel="noopener noreferrer"
class="result-title-link one-line"
>
<span class="result-title">{{ result.title }}</span>
</a>
<div v-else class="result-title-text one-line">
<span class="result-title">{{ result.title }}</span>
</div>
</div>
<div v-if="result.published_at || result.age" class="result-meta">
<span class="meta-item">
<t-icon name="time" class="meta-icon" />
{{ result.published_at ? formatDate(result.published_at) : result.age }}
</span>
</div>
</div>
</div>
</div>
</div>
<!-- Empty State -->
<div v-else class="empty-state">
{{ $t('chat.webSearchNoResults') }}
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import type { WebSearchResultsData, WebSearchResultItem } from '@/types/tool-results';
import { useI18n } from 'vue-i18n';
interface Props {
data: WebSearchResultsData;
}
const props = defineProps<Props>();
const { t, locale } = useI18n();
const results = computed(() => props.data.results || []);
// Group results by source first, then by domain if source is missing
type Group = { key: string; label: string; items: WebSearchResultItem[] };
const groupedResults = computed<Group[]>(() => {
const list = results.value || [];
const groupsMap: Record<string, Group> = {};
for (const item of list) {
const source = (item as any).source as string | undefined;
let key = '';
let label = '';
if (source && source.trim()) {
key = `src:${source.trim()}`;
label = source.trim();
} else {
// fallback to domain
const url = (item as any).url as string | undefined;
const hostname = url ? safeHostname(url) : t('chat.otherSource');
key = `dom:${hostname}`;
label = hostname;
}
if (!groupsMap[key]) {
groupsMap[key] = { key, label, items: [] };
}
groupsMap[key].items.push(item);
}
// Keep original order by first occurrence
const ordered: Group[] = [];
const seen = new Set<string>();
for (const item of list) {
const source = (item as any).source as string | undefined;
const url = (item as any).url as string | undefined;
const hostname = url ? safeHostname(url) : t('chat.otherSource');
const key = source && source.trim() ? `src:${source.trim()}` : `dom:${hostname}`;
if (!seen.has(key)) {
seen.add(key);
if (groupsMap[key]) ordered.push(groupsMap[key]);
}
}
return ordered;
});
const formatUrl = (url: string): string => {
try {
const urlObj = new URL(url);
return urlObj.hostname + urlObj.pathname;
} catch {
return url;
}
};
const safeHostname = (url: string): string => {
try {
const urlObj = new URL(url);
return urlObj.hostname;
} catch {
return t('chat.otherSource');
}
};
const truncateContent = (content: string, maxLength: number = 300): string => {
if (!content) return '';
if (content.length <= maxLength) return content;
return content.substring(0, maxLength) + '...';
};
const formatDate = (dateStr: string): string => {
try {
const date = new Date(dateStr);
return date.toLocaleDateString(locale.value || 'zh-CN', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
} catch {
return dateStr;
}
};
</script>
<style lang="less" scoped>
@import './tool-results.less';
.web-search-results {
display: flex;
flex-direction: column;
padding: 0 0 0 12px;
gap: 4px;
}
.results-groups {
display: flex;
flex-direction: column;
gap: 4px;
}
.results-group {
display: flex;
flex-direction: column;
gap: 3px;
}
.group-header {
display: flex;
align-items: center;
gap: 6px;
font-size: var(--app-text-sm);
color: var(--td-text-color-secondary);
/* Align with title start (after index column) */
padding-left: 34px;
}
.group-intro {
color: var(--td-text-color-secondary);
}
.group-source {
display: inline-flex;
align-items: center;
padding: 1px 6px;
border-radius: var(--app-radius-xs);
background: var(--td-bg-color-secondarycontainer);
border: 1px solid var(--td-component-stroke);
color: var(--td-text-color-primary);
font-weight: 600;
}
.group-count {
font-size: var(--app-text-sm);
color: var(--td-text-color-secondary);
}
.results-list {
display: flex;
flex-direction: column;
gap: 3px;
}
.result-item {
background: var(--td-bg-color-container);
border: none;
border-radius: 0;
transition: none;
}
.result-header {
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 0;
padding: 2px 0;
:deep(a) {
pointer-events: auto;
}
}
.result-index {
font-size: var(--app-text-xs);
font-weight: 600;
color: var(--td-text-color-placeholder);
flex-shrink: 0;
min-width: 24px;
text-align: right;
}
.result-title-link {
display: flex;
align-items: baseline;
gap: 6px;
flex: 1;
text-decoration: none;
color: var(--td-text-color-primary);
transition: color var(--app-motion-fast) ease;
&:hover {
color: var(--td-brand-color);
.result-title {
text-decoration: underline;
}
}
}
.result-title {
font-size: var(--app-text-sm);
font-weight: 500;
line-height: 1.4;
color: inherit;
flex: 1;
word-break: break-word;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.one-line {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.result-title-text {
display: flex;
align-items: baseline;
flex: 1;
.result-title {
font-size: var(--app-text-sm);
font-weight: 500;
line-height: 1.4;
color: var(--td-text-color-primary);
}
}
.result-meta {
display: flex;
align-items: center;
gap: 8px;
margin-top: 4px;
padding-top: 4px;
border-top: 1px solid var(--td-bg-color-secondarycontainer);
font-size: var(--app-text-2xs);
color: var(--td-text-color-placeholder);
.meta-item {
display: flex;
align-items: center;
gap: 3px;
}
.meta-icon {
font-size: var(--app-text-2xs);
}
}
.empty-state {
padding: 16px;
text-align: center;
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
font-style: italic;
background: var(--td-bg-color-secondarycontainer);
border-radius: var(--app-radius-sm);
border: 1px dashed var(--td-component-stroke);
}
</style>
@@ -0,0 +1,318 @@
<template>
<div class="wiki-edit-result">
<div class="result-card wiki-card">
<div class="result-header wiki-header">
<div class="result-title">
<span class="wiki-icon" :class="actionClass">{{ actionIcon }}</span>
<span class="wiki-title-text">{{ headerTitle }}</span>
</div>
<div class="result-meta">
<span class="action-badge" :class="actionClass">{{ actionLabel }}</span>
</div>
</div>
<div class="result-content expanded">
<div class="info-section">
<!-- wiki_write_page -->
<template v-if="data.display_type === 'wiki_write_page'">
<div class="info-field">
<span class="field-label">{{ $t('chat.wikiFieldSlug') }}</span>
<span class="field-value"><code>{{ data.slug }}</code></span>
</div>
<div class="info-field">
<span class="field-label">{{ $t('chat.wikiFieldTitle') }}</span>
<span class="field-value">{{ data.title }}</span>
</div>
<div class="info-field">
<span class="field-label">{{ $t('chat.wikiFieldPageType') }}</span>
<span class="field-value"><code>{{ data.page_type }}</code></span>
</div>
<div class="info-field">
<span class="field-label">{{ $t('chat.wikiFieldSummary') }}</span>
<span class="field-value">{{ data.summary }}</span>
</div>
</template>
<!-- wiki_replace_text -->
<template v-else-if="data.display_type === 'wiki_replace_text'">
<div class="info-field">
<span class="field-label">{{ $t('chat.wikiFieldSlug') }}</span>
<span class="field-value"><code>{{ data.slug }}</code></span>
</div>
<div class="info-field" v-if="data.title">
<span class="field-label">{{ $t('chat.wikiFieldTitle') }}</span>
<span class="field-value">{{ data.title }}</span>
</div>
<div class="diff-block">
<div class="diff-line diff-old">
<span class="diff-marker">-</span>
<span class="diff-text">{{ data.old_text }}</span>
</div>
<div class="diff-line diff-new">
<span class="diff-marker">+</span>
<span class="diff-text">{{ data.new_text }}</span>
</div>
</div>
</template>
<!-- wiki_rename_page -->
<template v-else-if="data.display_type === 'wiki_rename_page'">
<div class="info-field" v-if="data.title">
<span class="field-label">{{ $t('chat.wikiFieldTitle') }}</span>
<span class="field-value">{{ data.title }}</span>
</div>
<div class="rename-visual">
<code class="slug-old">{{ data.old_slug }}</code>
<span class="rename-arrow">→</span>
<code class="slug-new">{{ data.new_slug }}</code>
</div>
<div class="info-field" v-if="data.updated_count > 0">
<span class="field-label">{{ $t('chat.wikiFieldAffectedPages') }}</span>
<span class="field-value">{{ $t('chat.wikiAffectedCount', { count: data.updated_count }) }}</span>
</div>
<div class="affected-list" v-if="data.affected_pages?.length">
<code v-for="slug in data.affected_pages" :key="slug" class="affected-slug">{{ slug }}</code>
</div>
</template>
<!-- wiki_delete_page -->
<template v-else-if="data.display_type === 'wiki_delete_page'">
<div class="info-field">
<span class="field-label">{{ $t('chat.wikiFieldSlug') }}</span>
<span class="field-value"><code>{{ data.slug }}</code></span>
</div>
<div class="info-field" v-if="data.title">
<span class="field-label">{{ $t('chat.wikiFieldTitle') }}</span>
<span class="field-value">{{ data.title }}</span>
</div>
<div class="info-field" v-if="data.updated_count > 0">
<span class="field-label">{{ $t('chat.wikiFieldAffectedPages') }}</span>
<span class="field-value">{{ $t('chat.wikiAffectedCount', { count: data.updated_count }) }}</span>
</div>
<div class="affected-list" v-if="data.affected_pages?.length">
<code v-for="slug in data.affected_pages" :key="slug" class="affected-slug">{{ slug }}</code>
</div>
</template>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { WikiEditData } from '@/types/tool-results';
const props = defineProps<{
data: WikiEditData;
}>();
const { t } = useI18n();
const actionIcon = computed(() => {
switch (props.data.display_type) {
case 'wiki_write_page': return (props.data as any).action === 'created' ? '✦' : '✎';
case 'wiki_replace_text': return '⇄';
case 'wiki_rename_page': return '↻';
case 'wiki_delete_page': return '✕';
default: return '•';
}
});
const actionClass = computed(() => {
switch (props.data.display_type) {
case 'wiki_write_page':
return (props.data as any).action === 'created' ? 'created' : 'updated';
case 'wiki_replace_text': return 'updated';
case 'wiki_rename_page': return 'renamed';
case 'wiki_delete_page': return 'deleted';
default: return '';
}
});
const actionLabel = computed(() => {
switch (props.data.display_type) {
case 'wiki_write_page':
return (props.data as any).action === 'created'
? t('chat.wikiActionCreated')
: t('chat.wikiActionUpdated');
case 'wiki_replace_text': return t('chat.wikiActionUpdated');
case 'wiki_rename_page': return t('chat.wikiActionRenamed');
case 'wiki_delete_page': return t('chat.wikiActionDeleted');
default: return '';
}
});
const headerTitle = computed(() => {
switch (props.data.display_type) {
case 'wiki_write_page': return t('chat.wikiWritePageTitle');
case 'wiki_replace_text': return t('chat.wikiReplaceTextTitle');
case 'wiki_rename_page': return t('chat.wikiRenamePageTitle');
case 'wiki_delete_page': return t('chat.wikiDeletePageTitle');
default: return 'Wiki';
}
});
</script>
<style lang="less" scoped>
@import './tool-results.less';
.wiki-edit-result {
display: flex;
flex-direction: column;
gap: 8px;
}
.wiki-card {
margin: 0 8px 8px 8px;
}
.wiki-header {
.wiki-icon {
font-size: var(--app-text-base);
width: 20px;
height: 20px;
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: var(--app-radius-xs);
flex-shrink: 0;
&.created {
color: var(--td-success-color);
background: rgba(0, 168, 112, 0.1);
}
&.updated {
color: var(--td-brand-color);
background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
}
&.renamed {
color: var(--td-warning-color);
background: rgba(255, 152, 0, 0.1);
}
&.deleted {
color: var(--td-error-color);
background: rgba(227, 77, 89, 0.1);
}
}
.wiki-title-text {
font-size: var(--app-text-md);
font-weight: 500;
color: var(--td-text-color-primary);
}
}
.action-badge {
font-size: var(--app-text-xs);
font-weight: 600;
padding: 2px 8px;
border-radius: var(--app-radius-lg);
line-height: 1.5;
&.created {
color: var(--td-success-color);
background: rgba(0, 168, 112, 0.1);
border: 1px solid rgba(0, 168, 112, 0.2);
}
&.updated {
color: var(--td-brand-color);
background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
border: 1px solid color-mix(in srgb, var(--td-brand-color) 20%, transparent);
}
&.renamed {
color: var(--td-warning-color);
background: rgba(255, 152, 0, 0.1);
border: 1px solid rgba(255, 152, 0, 0.2);
}
&.deleted {
color: var(--td-error-color);
background: rgba(227, 77, 89, 0.1);
border: 1px solid rgba(227, 77, 89, 0.2);
}
}
.diff-block {
margin-top: 8px;
border: 1px solid @card-border;
border-radius: var(--app-radius-xs);
overflow: hidden;
font-family: var(--app-font-family-mono);
font-size: var(--app-text-sm);
}
.diff-line {
display: flex;
gap: 8px;
padding: 6px 10px;
line-height: 1.5;
&.diff-old {
background: rgba(227, 77, 89, 0.06);
color: var(--td-error-color);
border-bottom: 1px solid @card-border;
}
&.diff-new {
background: rgba(0, 168, 112, 0.06);
color: var(--td-success-color);
}
}
.diff-marker {
font-weight: 700;
flex-shrink: 0;
width: 14px;
text-align: center;
}
.diff-text {
word-break: break-word;
color: var(--td-text-color-primary);
}
.rename-visual {
display: flex;
align-items: center;
gap: 10px;
padding: 8px 0;
flex-wrap: wrap;
.slug-old {
text-decoration: line-through;
opacity: 0.6;
}
.slug-new {
color: var(--td-success-color);
font-weight: 600;
}
.rename-arrow {
font-size: var(--app-text-xl);
color: var(--td-text-color-placeholder);
}
}
.affected-list {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin-top: 6px;
padding-left: 90px;
.affected-slug {
font-size: var(--app-text-xs);
padding: 2px 6px;
border-radius: 3px;
background: var(--td-bg-color-secondarycontainer);
border: 1px solid @card-border;
}
}
code {
font-family: var(--app-font-family-mono);
font-size: var(--app-text-xs);
background: var(--td-bg-color-secondarycontainer);
padding: 2px 5px;
border-radius: 3px;
color: var(--td-text-color-primary);
}
</style>
@@ -0,0 +1,68 @@
<template>
<div class="sandbox-files-result">
<ResultRow
:index="1"
:title="title"
:meta="meta"
:popup-key="path"
:show-popup="false"
/>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { formatFileSize } from '@/utils/files'
import type { WriteSandboxFileData } from '@/types/tool-results'
import ResultRow from './ResultRow.vue'
const props = defineProps<{
data: WriteSandboxFileData | Record<string, unknown>
}>()
const { t } = useI18n()
const record = computed(() => (props.data || {}) as Record<string, unknown>)
const path = computed(() => String(record.value.path || ''))
const title = computed(() => {
const name = String(record.value.name || '').trim()
if (name) return name
const parts = path.value.split('/').filter(Boolean)
const isEdit = record.value.display_type === 'edit_sandbox_file'
return parts[parts.length - 1] || path.value || t(isEdit ? 'agentStream.sandboxFiles.edited' : 'agentStream.sandboxFiles.wrote')
})
const meta = computed(() => {
const size = record.value.size
const replacements = record.value.replacements
const added = record.value.added_lines
const removed = record.value.removed_lines
const isEdit = record.value.display_type === 'edit_sandbox_file' || typeof replacements === 'number'
const parts = [t(isEdit ? 'agentStream.sandboxFiles.edited' : 'agentStream.sandboxFiles.wrote')]
const addedN = typeof added === 'number' && Number.isFinite(added) ? added : 0
const removedN = typeof removed === 'number' && Number.isFinite(removed) ? removed : 0
if (addedN > 0) parts.push(`+${addedN}`)
if (removedN > 0) parts.push(`-${removedN}`)
if (isEdit && typeof replacements === 'number' && Number.isFinite(replacements)) {
parts.push(t('agentStream.sandboxFiles.replacements', { count: replacements }))
}
if (typeof size === 'number' && Number.isFinite(size) && size >= 0) {
parts.push(size === 0 ? '0 B' : formatFileSize(size))
}
if (path.value) parts.push(path.value)
return parts.join(' · ')
})
</script>
<style lang="less" scoped>
@import './tool-results.less';
.sandbox-files-result {
display: flex;
flex-direction: column;
gap: 8px;
}
</style>
@@ -0,0 +1,38 @@
/**
* Strip ingestion noise from chunk text before display: YAML frontmatter,
* markdown footnote reference markers (e.g. `^(\[4\])`, `[^4]`, `[4]`) and
* stray backslash escapes. Keeps human-readable prose intact.
*/
function stripNoise(text: string): string {
let s = text || '';
// Leading YAML frontmatter block: --- ... ---
s = s.replace(/^\uFEFF?\s*---[\s\S]*?\n---\s*/, '');
// Inline frontmatter leftovers dragged into a single-line snippet
s = s.replace(
/-{2,}\s*((?:title|author|url|date|tags?|description)\s*:[\s\S]*?)-{2,}/gi,
' ',
);
// Footnote / citation markers: ^(\[4\]) / ^[4] / [^4] / [4]
s = s.replace(/\^?\(?\s*\\?\[\s*\^?\d+\s*\\?\]\s*\)?/g, '');
// Unescape common markdown backslash escapes
s = s.replace(/\\([\\[\]()*_#`~\-+.!>])/g, '$1');
return s;
}
/** Clean multi-line content for full display, preserving paragraph breaks. */
export function cleanContent(text: string): string {
return stripNoise(text)
.replace(/[ \t]+\n/g, '\n')
.replace(/\n{3,}/g, '\n\n')
.trim();
}
/** Clean a snippet down to a single, whitespace-collapsed line. */
export function cleanSnippet(text: string): string {
return stripNoise(text).replace(/\s+/g, ' ').trim();
}
@@ -0,0 +1,313 @@
/**
* Tool Results Shared Styles
* Common styles for all tool result components
*/
// Color scheme for relevance levels
@relevance-high: var(--td-success-color);
@relevance-medium: var(--td-warning-color);
@relevance-low: var(--td-text-color-placeholder);
@relevance-weak: var(--td-text-color-disabled);
// Card colors
@card-bg: var(--td-bg-color-container);
@card-border: var(--td-component-stroke);
@card-hover-border: var(--td-brand-color);
@card-radius: 6px;
@card-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
@card-shadow-hover: 0 2px 6px color-mix(in srgb, var(--td-brand-color) 8%, transparent);
// Animation timing
@transition-time: 0.2s;
// Tool result container
.tool-result-container {
margin: 12px 0;
}
// Relevance badge styles
.relevance-badge {
display: inline-flex;
align-items: center;
padding: 2px 6px;
border-radius: 3px;
font-size: var(--app-text-xs);
font-weight: 600;
gap: 3px;
line-height: 1.4;
&.high {
background-color: rgba(0, 168, 112, 0.12);
color: @relevance-high;
}
&.medium {
background-color: rgba(255, 152, 0, 0.12);
color: var(--td-warning-color);
}
&.low {
background-color: rgba(117, 117, 117, 0.12);
color: @relevance-low;
}
&.weak {
background-color: rgba(189, 189, 189, 0.12);
color: var(--td-text-color-secondary);
}
}
// Match type badge
.match-type-badge {
display: inline-flex;
align-items: center;
padding: 2px 6px;
border-radius: 3px;
font-size: var(--app-text-2xs);
background-color: var(--td-bg-color-secondarycontainer);
color: var(--td-text-color-secondary);
gap: 2px;
line-height: 1.4;
}
// Result card
.result-card {
background: @card-bg;
border: 1px solid @card-border;
border-radius: @card-radius;
margin-bottom: 0;
overflow: hidden;
transition: border-color @transition-time ease, box-shadow @transition-time ease;
box-shadow: @card-shadow;
&:hover {
border-color: @card-hover-border;
box-shadow: @card-shadow-hover;
}
}
.result-header {
padding: 10px 12px;
cursor: pointer;
user-select: none;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
position: relative;
z-index: 1;
transition: background-color var(--app-motion-fast) ease;
&:hover {
background: color-mix(in srgb, var(--td-brand-color) 4%, transparent);
}
* {
pointer-events: none;
}
}
.result-title {
display: flex;
align-items: center;
gap: 6px;
flex: 1;
font-size: var(--app-text-md);
font-weight: 500;
line-height: 1.4;
}
.result-meta {
display: flex;
align-items: center;
gap: 6px;
font-size: var(--app-text-xs);
color: var(--td-text-color-secondary);
flex-shrink: 0;
}
.result-content {
padding: 0;
border-top: 1px solid @card-border;
background: var(--td-bg-color-container);
max-height: 0;
opacity: 0;
overflow: hidden;
transition: max-height @transition-time ease, opacity @transition-time ease, padding @transition-time ease;
&.expanded {
max-height: 2000px;
opacity: 1;
padding: 12px;
}
}
.expand-icon {
font-size: var(--app-text-sm);
color: var(--td-text-color-placeholder);
transition: transform var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
&.expanded {
transform: rotate(180deg);
}
}
// Info sections
.info-section {
margin-top: 12px;
&:first-child {
margin-top: 0;
}
}
.info-section-title {
font-size: var(--app-text-xs);
font-weight: 600;
color: var(--td-text-color-secondary);
text-transform: uppercase;
letter-spacing: 0.5px;
margin-bottom: 8px;
}
.info-field {
display: flex;
gap: 8px;
margin-bottom: 6px;
font-size: var(--app-text-sm);
line-height: 1.5;
.field-label {
color: var(--td-text-color-secondary);
min-width: 80px;
flex-shrink: 0;
font-weight: 500;
}
.field-value {
color: var(--td-text-color-primary);
flex: 1;
word-break: break-word;
}
}
// Statistics card (for KB counts, etc.)
.stats-card {
background: color-mix(in srgb, var(--td-brand-color) 4%, transparent);
border: 1px solid color-mix(in srgb, var(--td-brand-color) 15%, transparent);
border-radius: @card-radius;
padding: 10px 12px;
margin-bottom: 10px;
}
.stats-title {
font-size: var(--app-text-sm);
font-weight: 600;
color: var(--td-text-color-primary);
margin-bottom: 6px;
}
.stats-list {
display: flex;
flex-direction: column;
gap: 4px;
}
.stats-item {
font-size: var(--app-text-xs);
color: var(--td-text-color-secondary);
display: flex;
justify-content: space-between;
line-height: 1.5;
}
// Grid layout for cards
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 10px;
margin-top: 8px;
}
// List item
.list-item {
display: flex;
flex-direction: column;
gap: 4px;
padding: 6px 0;
border-bottom: 1px solid var(--td-component-stroke);
&:last-child {
border-bottom: none;
}
}
// Content preview (truncated)
.content-preview {
font-size: var(--app-text-sm);
color: var(--td-text-color-primary);
line-height: 1.6;
max-height: 60px;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
}
// Full content
.full-content {
font-size: var(--app-text-sm);
color: var(--td-text-color-primary);
line-height: 1.6;
white-space: pre-wrap;
word-break: break-word;
padding: 10px;
background: var(--td-bg-color-secondarycontainer);
border-radius: var(--app-radius-xs);
border: 1px solid @card-border;
}
// Action buttons
.action-button {
padding: 4px 10px;
font-size: var(--app-text-xs);
border-radius: var(--app-radius-xs);
border: 1px solid @card-border;
background: var(--td-bg-color-container);
color: var(--td-text-color-secondary);
cursor: pointer;
transition: all var(--app-motion-fast) ease;
font-weight: 500;
&:hover {
border-color: @card-hover-border;
color: @card-hover-border;
background: color-mix(in srgb, var(--td-brand-color) 4%, transparent);
}
}
// Empty state
.empty-state {
padding: 20px;
text-align: center;
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
font-style: italic;
background: var(--td-bg-color-secondarycontainer);
border-radius: @card-radius;
border: 1px dashed @card-border;
}
// Code block
.code-block {
font-family: var(--app-font-family-mono);
font-size: var(--app-text-xs);
background: var(--td-bg-color-secondarycontainer);
padding: 8px;
border-radius: var(--app-radius-xs);
border: 1px solid @card-border;
overflow-x: auto;
line-height: 1.5;
}
@@ -0,0 +1,487 @@
<template>
<div class="user_msg_container" ref="containerRef" :class="{ 'is-embedded': embeddedMode, 'is-actions-pinned': rewindConfirmOpen }">
<!-- 显示@的知识库和文件 -->
<div v-if="mentioned_items && mentioned_items.length > 0" class="mentioned_items">
<span v-for="item in mentioned_items" :key="item.id" class="mentioned_tag" :class="[
mentionTagClass(item)
]">
<span class="tag_icon">
<t-icon v-if="item.type === 'kb'" :name="item.kb_type === 'faq' ? 'chat-bubble-help' : 'folder'" />
<t-icon v-else :name="mentionTagIcon(item)" />
</span>
<span class="tag_name">{{ item.name }}</span>
</span>
</div>
<!-- 显示上传的图片 -->
<div v-if="hasImages" class="user_images">
<img v-for="(img, idx) in props.images" :key="idx" :src="img.url" class="user_image_thumb"
@click="previewImage($event)" />
</div>
<!-- 显示上传的附件 -->
<div v-if="hasAttachments" class="user_attachments">
<div v-for="(att, idx) in props.attachments" :key="idx"
class="user_attachment_card"
:class="{ 'is-previewable': canPreviewAttachment(att) }"
@click="openAttachmentPreview(att)">
<ArtifactFileIcon :file-name="att.file_name" />
<div class="attachment_card_info">
<div class="attachment_card_name" :title="att.file_name">{{ att.file_name }}</div>
<div v-if="att.file_size" class="attachment_card_meta">{{ formatFileSize(att.file_size) }}</div>
</div>
</div>
</div>
<div class="user_msg">
{{ content }}
</div>
<div v-if="timestamp || content || canFork || canRewind" class="user_msg_meta">
<time v-if="timestamp" class="user_msg_time" :datetime="timestamp.datetime" :title="fullTimestamp">
{{ timestamp.kind === 'today' ? timestamp.time : fullTimestamp }}
</time>
<div v-if="content || canFork || canRewind" class="user_msg_actions">
<t-tooltip v-if="content" :content="t('agent.copy')">
<button type="button" class="user_msg_action" :aria-label="t('agent.copy')" @click="handleCopy">
<ChatActionIcon name="copy" />
</button>
</t-tooltip>
<t-tooltip v-if="canFork" :content="forkTooltip">
<button type="button" class="user_msg_action" :aria-label="forkTooltip" @click="emit('fork', messageId)">
<ChatActionIcon name="git-branch" />
</button>
</t-tooltip>
<t-popconfirm
v-if="canRewind"
:confirm-btn="{ content: t('chat.rewind.confirmButton'), theme: 'danger', size: 'small' }"
:cancel-btn="{ content: t('chat.rewind.cancelButton'), size: 'small' }"
theme="warning"
placement="top"
:show-arrow="false"
overlay-class-name="wk-popover chat-rewind-popconfirm"
@visible-change="(visible) => (rewindConfirmOpen = visible)"
@confirm="emit('rewind', messageId)"
>
<template #content>
<div class="chat-rewind-confirm__title">{{ t('chat.rewind.confirmTitle') }}</div>
<div class="chat-rewind-confirm__body">{{ t('chat.rewind.confirmBody') }}</div>
</template>
<t-tooltip :content="rewindTooltip">
<button type="button" class="user_msg_action" :class="{ 'is-active': rewindConfirmOpen }" :aria-label="rewindTooltip" @click.stop>
<ChatActionIcon name="rollback" />
</button>
</t-tooltip>
</t-popconfirm>
</div>
</div>
<div v-if="steerFailed" class="steer-failure" role="status">
<span>{{ t('input.messages.steerFailed') }}</span>
<t-tooltip :content="t('input.steerRetry')"><button type="button" :aria-label="t('input.steerRetry')" @click="emit('retry-steer')"><t-icon name="refresh" /></button></t-tooltip>
<t-tooltip :content="t('common.remove')"><button type="button" :aria-label="t('common.remove')" @click="emit('remove-steer')"><t-icon name="close" /></button></t-tooltip>
</div>
<picturePreview :reviewImg="reviewImg" :reviewUrl="reviewUrl" @closePreImg="closePreImg" />
</div>
</template>
<script setup>
import { computed, ref, watch, onMounted, nextTick } from "vue";
import { hydrateProtectedFileImages } from '@/utils/security';
import picturePreview from '@/components/picture-preview.vue';
import ArtifactFileIcon from './ArtifactFileIcon.vue';
import ChatActionIcon from '@/components/ChatActionIcon.vue';
import { useI18n } from 'vue-i18n';
import { useChatAttachmentPreviewDrawer } from '@/composables/useChatAttachmentPreviewDrawer';
import { isPreviewableAttachment, resolveAttachmentFileType } from '@/utils/attachmentPreview';
import { SKILL_ICON } from '@/types/mention';
import { copyWithToast } from '@/utils/clipboard';
import { formatMessageTimestamp, getConversationTimestampModel } from '@/utils/messageTimestamp';
const emit = defineEmits(['retry-steer', 'remove-steer', 'fork', 'rewind']);
const { t } = useI18n();
const mentionTagClass = (item) => {
if (item.type === 'kb') return item.kb_type === 'faq' ? 'faq-tag' : 'kb-tag';
return `${item.type || 'file'}-tag`;
};
const mentionTagIcon = (item) => {
if (item.type === 'tag') return 'tag';
if (item.type === 'mcp') return 'tools';
if (item.type === 'skill') return SKILL_ICON;
return 'file';
};
const props = defineProps({
steerFailed: { type: Boolean, default: false },
content: {
type: String,
required: false
},
mentioned_items: {
type: Array,
required: false,
default: () => []
},
images: {
type: Array,
required: false,
default: () => []
},
attachments: {
type: Array,
required: false,
default: () => []
},
channel: {
type: String,
required: false,
default: ''
},
embeddedMode: {
type: Boolean,
default: false
},
sessionId: {
type: String,
default: ''
},
messageId: {
type: String,
default: ''
},
createdAt: {
type: String,
default: ''
},
canFork: {
type: Boolean,
default: false
},
canRewind: {
type: Boolean,
default: false
}
});
const canFork = computed(() => props.canFork === true && !props.embeddedMode);
const canRewind = computed(() => props.canRewind === true && !props.embeddedMode);
const forkTooltip = '从这里分叉出新会话';
const timestamp = computed(() => getConversationTimestampModel(props.createdAt));
const fullTimestamp = computed(() => formatMessageTimestamp(props.createdAt));
const handleCopy = () => copyWithToast(props.content, 'common.copySuccess', 'common.copyFailed');
const rewindTooltip = computed(() => t('chat.rewind.tooltip'));
const rewindConfirmOpen = ref(false);
const attachmentPreviewDrawer = useChatAttachmentPreviewDrawer();
const channelLabelMap = {
web: () => t('chat.channelWeb'),
api: () => t('chat.channelApi'),
im: () => t('chat.channelIm'),
};
const channelLabel = computed(() => {
if (!props.channel) return '';
const label = channelLabelMap[props.channel];
return typeof label === 'function' ? label() : (label || props.channel);
});
const channelClass = computed(() => props.channel ? `channel-${props.channel}` : '');
const containerRef = ref(null);
const hasImages = computed(() => props.images && props.images.length > 0);
const hasAttachments = computed(() => props.attachments && props.attachments.length > 0);
const formatFileSize = (bytes) => {
if (!bytes) return '';
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
};
const canPreviewAttachment = (attachment) => {
return Boolean(props.sessionId) && isPreviewableAttachment(attachment);
};
const openAttachmentPreview = (attachment) => {
if (!canPreviewAttachment(attachment) || !attachmentPreviewDrawer) return;
attachmentPreviewDrawer.open({
sessionId: props.sessionId,
attachmentId: attachment.id,
fileName: attachment.file_name,
fileType: resolveAttachmentFileType(attachment.file_name, attachment.file_type),
});
};
const hydrateImages = async () => {
await nextTick();
await hydrateProtectedFileImages(containerRef.value);
};
watch(() => props.images, hydrateImages);
onMounted(hydrateImages);
const reviewImg = ref(false);
const reviewUrl = ref('');
const previewImage = (event) => {
const src = event.target?.src;
if (src) {
reviewUrl.value = src;
reviewImg.value = true;
}
};
const closePreImg = () => {
reviewImg.value = false;
reviewUrl.value = '';
};
</script>
<style scoped lang="less">
@import '../../../components/css/chat-resource-chips.less';
.user_msg_container {
position: relative;
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 6px;
width: 100%;
}
.mentioned_items {
.chat-mentioned-items(flex-end);
}
.mentioned_tag {
.chat-mentioned-tag();
}
.user_msg_container {
&.is-embedded {
.user_msg {
max-width: 100%;
}
}
}
.user_msg {
width: max-content;
max-width: min(76%, 820px);
display: flex;
padding: 8px 12px;
flex-direction: column;
justify-content: center;
align-items: flex-start;
gap: 4px;
flex: 1 0 0;
border-radius: var(--app-radius-md);
background: var(--td-bg-color-secondarycontainer);
margin-left: auto;
color: var(--td-text-color-primary);
font-size: var(--app-text-xl);
line-height: 1.6;
text-align: left;
word-break: break-word;
overflow-wrap: anywhere;
box-sizing: border-box;
white-space: pre-wrap;
}
.user_images {
display: flex;
flex-wrap: wrap;
gap: 6px;
justify-content: flex-end;
max-width: 100%;
}
.user_attachments {
display: flex;
flex-wrap: wrap;
gap: 8px;
justify-content: flex-end;
max-width: 100%;
}
.user_attachment_card {
display: flex;
align-items: center;
gap: 10px;
box-sizing: border-box;
width: 240px;
max-width: 100%;
padding: 8px 12px 8px 8px;
border-radius: var(--app-radius-md);
background: var(--td-bg-color-secondarycontainer);
cursor: default;
&.is-previewable {
cursor: pointer;
transition: background var(--app-motion-fast) ease;
&:hover {
background: var(--td-bg-color-secondarycontainer-hover);
}
}
.attachment_card_info {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
}
.attachment_card_name {
font-size: var(--app-text-md);
font-weight: 500;
line-height: 1.35;
color: var(--td-text-color-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.attachment_card_meta {
margin-top: 2px;
font-size: var(--app-text-sm);
line-height: 1.3;
color: var(--td-text-color-placeholder);
white-space: nowrap;
}
}
.user_image_thumb {
width: 120px;
height: 120px;
object-fit: cover;
border-radius: var(--app-radius-sm);
cursor: pointer;
border: 1px solid var(--td-border-level-2-color);
transition: opacity var(--app-motion-base);
&:hover {
opacity: 0.85;
}
}
.channel_tag {
display: inline-flex;
align-items: center;
padding: 1px 6px;
border-radius: 3px;
font-size: var(--app-text-xs);
font-weight: 500;
line-height: 18px;
background: var(--td-bg-color-secondarycontainer);
color: var(--td-text-color-placeholder);
border: 1px solid var(--td-border-level-2-color);
&.channel-web {
color: var(--td-brand-color);
background: var(--td-brand-color-light);
border-color: var(--td-brand-color-2);
}
&.channel-api {
color: var(--td-success-color);
background: var(--td-success-color-1);
border-color: var(--td-success-color-2);
}
&.channel-im {
color: var(--td-warning-color);
background: var(--td-warning-color-1);
border-color: var(--td-warning-color-2);
}
}
html[theme-mode="dark"] {
.user_msg {
background: var(--td-bg-color-secondarycontainer);
color: var(--td-text-color-primary);
}
}
</style>
<style scoped>
.steer-failure { display: flex; align-items: center; justify-content: flex-end; gap: 4px; font-size: var(--app-text-sm); color: var(--td-text-color-secondary); margin-bottom: 4px; }
.steer-failure { margin-top: 6px; color: var(--td-error-color); }
.steer-failure button { display: inline-flex; align-items: center; justify-content: center; width: 26px; height: 26px; border: 0; border-radius: var(--app-radius-sm); background: transparent; color: inherit; cursor: pointer; }
.steer-failure button:hover { background: var(--td-bg-color-secondarycontainer); }
.user_msg_meta {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 8px;
min-height: 28px;
padding-right: 4px;
color: var(--td-text-color-placeholder);
opacity: 0;
pointer-events: none;
transition: opacity 140ms ease;
}
.user_msg_time {
font-size: var(--app-text-sm);
font-variant-numeric: tabular-nums;
line-height: 20px;
}
.user_msg_actions {
display: flex;
align-items: center;
gap: 2px;
color: color-mix(in srgb, var(--td-text-color-primary) 55%, transparent);
}
.user_msg_container:hover .user_msg_meta,
.user_msg_container:focus-within .user_msg_meta,
.user_msg_container.is-actions-pinned .user_msg_meta {
opacity: 1;
pointer-events: auto;
}
.user_msg_action {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
padding: 0;
border: 0;
border-radius: var(--app-radius-sm);
background: transparent;
color: inherit;
font-size: var(--app-text-xl);
cursor: pointer;
}
.user_msg_action :deep(.chat-action-icon) {
display: block;
width: 16px;
height: 16px;
flex-shrink: 0;
}
.user_msg_action:hover,
.user_msg_action.is-active {
color: var(--td-text-color-secondary);
background: var(--td-bg-color-container-hover);
}
.user_msg_action:focus-visible {
outline: 2px solid var(--td-text-color-secondary);
outline-offset: 2px;
}
@media (hover: none) {
.user_msg_meta {
opacity: 1;
pointer-events: auto;
}
}
@media (prefers-reduced-motion: reduce) {
.user_msg_meta {
transition: none;
}
}
</style>
+51
View File
@@ -0,0 +1,51 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { resolveForkAffordance } from './forkPoint'
test('第一条 user 消息可以分叉', () => {
const messages = [
{ id: 'u1', role: 'user' },
{ id: 'a1', role: 'assistant' },
]
assert.deepEqual(resolveForkAffordance(messages, 'u1'), { canFork: true })
})
test('前置 assistant 无论有没有 checkpoint 都可以分叉', () => {
const messages = [
{ id: 'u1', role: 'user' },
{ id: 'a1', role: 'assistant' },
{ id: 'u2', role: 'user' },
]
assert.deepEqual(resolveForkAffordance(messages, 'u2'), { canFork: true })
})
test('assistant 消息可以分叉', () => {
const messages = [
{ id: 'u1', role: 'user' },
{ id: 'a1', role: 'assistant', is_completed: true },
]
assert.deepEqual(resolveForkAffordance(messages, 'a1'), { canFork: true })
})
test('未知角色不能作为分叉点', () => {
const messages = [
{ id: 'u1', role: 'user' },
{ id: 's1', role: 'system' },
]
assert.deepEqual(resolveForkAffordance(messages, 's1'), { canFork: false })
})
test('未知消息 ID 不能分叉', () => {
assert.deepEqual(
resolveForkAffordance([{ id: 'u1', role: 'user' }], 'nope'),
{ canFork: false },
)
})
test('未完成的 assistant 消息意味着本轮还在跑,不给分叉', () => {
const messages = [
{ id: 'u1', role: 'user' },
{ id: 'a1', role: 'assistant', is_completed: false },
]
assert.deepEqual(resolveForkAffordance(messages, 'u1'), { canFork: false })
})
+45
View File
@@ -0,0 +1,45 @@
/**
* Fork affordance rules, kept as a pure function so they can be tested without
* mounting the chat view.
*
* The backend re-derives all of this; this is purely so the UI can show the
* right button state without an extra round trip.
*
* User messages fork *at* the question (history excludes it, composer prefills
* it). Assistant messages fork *after* the answer (history includes it).
*/
export interface ForkCandidateMessage {
id?: unknown
role?: unknown
is_completed?: unknown
}
export interface ForkAffordance {
/** Whether the fork button should be offered on this message at all. */
canFork: boolean
}
const REFUSED: ForkAffordance = { canFork: false }
export function resolveForkAffordance(
messages: ForkCandidateMessage[],
messageId: string,
): ForkAffordance {
const index = messages.findIndex((m) => m.id === messageId)
if (index < 0) {
return REFUSED
}
// A turn still streaming means the source session holds an active sandbox
// lease. The backend would answer 409, so do not offer the button.
if (messages.some((m) => m.role === 'assistant' && m.is_completed === false)) {
return REFUSED
}
const target = messages[index]
if (target.role === 'assistant' || target.role === 'user') {
return { canFork: true }
}
return REFUSED
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,28 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { runInNewContext } from 'node:vm'
import test from 'node:test'
const source = readFileSync(new URL('./index.vue', import.meta.url), 'utf8')
const start = source.indexOf('const hostScope = props.embeddedMode')
const end = source.indexOf('const mcpServiceIds =', start)
assert.ok(start > 0 && end > start)
test('assistant page context does not replace or widen explicit KB, file and tag mentions', () => {
for (const mentionedItems of [
[],
[{ id: 'selected-kb', type: 'kb' }],
[{ id: 'doc', type: 'file' }],
[{ id: 'tag', type: 'tag', kb_id: 'selected-kb' }],
]) {
const result = runInNewContext(`${source.slice(start, end)}; ({ kbIds, knowledgeIds, tagIds, hostScope });`, {
props: { embeddedMode: true, hostScope: () => ({ knowledgeBaseIds: [], pageContext: { knowledge_base_id: 'page-kb' } }) },
useSettingsStoreInstance: { settings: { selectedKnowledgeBases: ['unrelated-sidebar-kb'], selectedFiles: ['unrelated-doc'] } },
pendingSuggestionKnowledgeBaseIds: [], mentionedItems,
})
assert.deepEqual(Array.from(result.kbIds), mentionedItems.filter(i => i.type === 'kb').map(i => i.id))
assert.deepEqual(Array.from(result.knowledgeIds), mentionedItems.filter(i => i.type === 'file').map(i => i.id))
assert.deepEqual(Array.from(result.tagIds), mentionedItems.filter(i => i.type === 'tag').map(i => i.id))
assert.equal(result.hostScope.pageContext.knowledge_base_id, 'page-kb')
}
})
@@ -0,0 +1,23 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { rewindSkipMessage } from './rewindNotice'
const t = (key: string) => key
test('NO_SANDBOX maps to skipNoSandbox', () => {
assert.equal(rewindSkipMessage('NO_SANDBOX', t), 'chat.rewind.skipNoSandbox')
})
test('NO_CHECKPOINT maps to skipNoCheckpoint', () => {
assert.equal(rewindSkipMessage('NO_CHECKPOINT', t), 'chat.rewind.skipNoCheckpoint')
})
// A replaced sandbox fail-closes with a 409 rather than truncating, so it
// never arrives here as a skip reason.
test('unknown code falls back to generic skipped copy', () => {
assert.equal(rewindSkipMessage('WEIRD', t), 'chat.rewind.skipped')
})
test('empty reason returns empty so the UI can skip the workspace notice', () => {
assert.equal(rewindSkipMessage('', t), '')
})
+21
View File
@@ -0,0 +1,21 @@
/**
* Maps a rewind skip reason from the API to i18n copy.
*
* An empty reason means the workspace was reset; the caller should not show
* a skip notice in that case.
*/
export type RewindCopyFn = (key: string) => string
export function rewindSkipMessage(reason: string, t: RewindCopyFn): string {
if (!reason) {
return ''
}
switch (reason) {
case 'NO_SANDBOX':
return t('chat.rewind.skipNoSandbox')
case 'NO_CHECKPOINT':
return t('chat.rewind.skipNoCheckpoint')
default:
return t('chat.rewind.skipped')
}
}
+124
View File
@@ -0,0 +1,124 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import {
canReplaceRewindTranscript,
keepMessagesThroughRewindPoint,
rewindableMessageIds,
resolveRewindAffordance,
rewindBlockedByOutgoingWork,
rewindConflictI18nKey,
rewindHistoryHasMore,
rewindHttpConflictCode,
rewindPrefillText,
shouldApplyRewindLocally,
} from './rewindView'
test('applies rewind UI only while still on the source session', () => {
assert.equal(shouldApplyRewindLocally('sess-1', 'sess-1'), true)
assert.equal(shouldApplyRewindLocally('sess-2', 'sess-1'), false)
assert.equal(shouldApplyRewindLocally('', 'sess-1'), false)
})
test('prefills only the user rewind point', () => {
assert.equal(rewindPrefillText('user', 'rewrite this'), 'rewrite this')
assert.equal(rewindPrefillText('assistant', 'keep this answer'), '')
assert.equal(rewindPrefillText('user', undefined), '')
})
test('blocks rewind while a send, stream, or IM recover is in flight', () => {
assert.equal(rewindBlockedByOutgoingWork({}), false)
assert.equal(rewindBlockedByOutgoingWork({ isReplying: true }), true)
assert.equal(rewindBlockedByOutgoingWork({ isStreaming: true }), true)
assert.equal(rewindBlockedByOutgoingWork({ isRecovering: true }), true)
})
test('replaces the transcript only after a successful reload on the source session', () => {
assert.equal(canReplaceRewindTranscript('sess-1', 'sess-1', undefined), true)
assert.equal(canReplaceRewindTranscript('sess-1', 'sess-1', new Error('network')), false)
assert.equal(canReplaceRewindTranscript('sess-2', 'sess-1', undefined), false)
})
test('history has more pages when the reload batch fills the limit', () => {
assert.equal(rewindHistoryHasMore(20, 20), true)
assert.equal(rewindHistoryHasMore(19, 20), false)
assert.equal(rewindHistoryHasMore(0, 20), false)
})
test('keeps messages through an assistant rewind point and drops a user point', () => {
const messages = [
{ id: 'u1', role: 'user' },
{ id: 'a1', role: 'assistant' },
{ id: 'u2', role: 'user' },
{ id: 'a2', role: 'assistant' },
]
assert.deepEqual(
keepMessagesThroughRewindPoint(messages, 'u2', 'user').map((m) => m.id),
['u1', 'a1'],
)
assert.deepEqual(
keepMessagesThroughRewindPoint(messages, 'a1', 'assistant').map((m) => m.id),
['u1', 'a1'],
)
})
test('offers rewind on user and assistant messages unless outgoing work or an incomplete turn', () => {
const messages = [
{ id: 'u1', role: 'user' },
{ id: 'a1', role: 'assistant', is_completed: true },
{ id: 'u2', role: 'user' },
]
assert.equal(resolveRewindAffordance(messages, 'u1').canRewind, true)
assert.equal(resolveRewindAffordance(messages, 'a1').canRewind, true)
assert.equal(resolveRewindAffordance(messages, 'u2').canRewind, true)
assert.equal(resolveRewindAffordance(messages, 'u1', { embeddedMode: true }).canRewind, false)
assert.equal(resolveRewindAffordance(messages, 'u1', { outgoingWork: true }).canRewind, false)
assert.equal(
resolveRewindAffordance(
[...messages, { id: 'a2', role: 'assistant', is_completed: false }],
'u1',
).canRewind,
false,
)
assert.equal(resolveRewindAffordance(messages, 'sys', { }).canRewind, false)
})
test('maps rewind HTTP conflicts onto dedicated copy', () => {
assert.equal(rewindHttpConflictCode({ status: 409, code: 'REWIND_NO_CHECKPOINT' }), 'REWIND_NO_CHECKPOINT')
assert.equal(rewindHttpConflictCode({ $httpStatus: 409, code: 'REWIND_SOURCE_BUSY' }), 'REWIND_SOURCE_BUSY')
assert.equal(rewindHttpConflictCode({ status: 500, code: 'REWIND_NO_CHECKPOINT' }), '')
assert.equal(rewindConflictI18nKey('REWIND_NO_CHECKPOINT'), 'chat.rewind.noCheckpoint')
assert.equal(rewindConflictI18nKey('REWIND_SANDBOX_REPLACED'), 'chat.rewind.sandboxReplaced')
assert.equal(rewindConflictI18nKey('REWIND_SOURCE_BUSY'), 'chat.rewind.busy')
assert.equal(rewindConflictI18nKey(''), 'chat.rewind.busy')
})
// The transcript resolves every row's control from this one set, so it has to
// answer exactly what the per-message check answers — and only walk once.
test('resolves every rewindable id in a single pass', () => {
const messages = [
{ id: 'u1', role: 'user' },
{ id: 'a1', role: 'assistant', is_completed: true },
{ id: 'u2', role: 'user' },
{ id: 'sys', role: 'system' },
{ id: '', role: 'user' },
]
assert.deepEqual([...rewindableMessageIds(messages)], ['u1', 'a1', 'u2'])
assert.deepEqual([...rewindableMessageIds(messages, { embeddedMode: true })], [])
assert.deepEqual([...rewindableMessageIds(messages, { outgoingWork: true })], [])
assert.deepEqual(
[...rewindableMessageIds([...messages, { id: 'a2', role: 'assistant', is_completed: false }])],
[],
'an unfinished turn withdraws the control from the whole transcript',
)
})
test('withholds rewind from the newest assistant answer', () => {
const messages = [
{ id: 'u1', role: 'user' },
{ id: 'a1', role: 'assistant', is_completed: true },
{ id: 'u2', role: 'user' },
{ id: 'a2', role: 'assistant', is_completed: true },
{ id: 'sys', role: 'system' },
]
assert.deepEqual([...rewindableMessageIds(messages)], ['u1', 'a1', 'u2'])
})
+124
View File
@@ -0,0 +1,124 @@
/**
* Client-side rewind helpers. The HTTP call mutates the source session on
* the server; these decide whether that result may touch the live chat view.
*/
export function shouldApplyRewindLocally(currentSessionId: string, sourceSessionId: string): boolean {
return Boolean(currentSessionId) && currentSessionId === sourceSessionId
}
export function rewindPrefillText(role: unknown, content: unknown): string {
if (role !== 'user') {
return ''
}
return String(content ?? '')
}
export function rewindBlockedByOutgoingWork(state: {
isReplying?: boolean
isStreaming?: boolean
isRecovering?: boolean
}): boolean {
return Boolean(state.isReplying || state.isStreaming || state.isRecovering)
}
/** Empty history is success (the conversation was cleared). A thrown reload is not. */
export function canReplaceRewindTranscript(
currentSessionId: string,
sourceSessionId: string,
reloadError: unknown,
): boolean {
if (reloadError) {
return false
}
return shouldApplyRewindLocally(currentSessionId, sourceSessionId)
}
export function rewindHistoryHasMore(batchLength: number, limit: number): boolean {
return batchLength >= limit
}
export function keepMessagesThroughRewindPoint<T extends { id?: unknown }>(
messages: T[],
messageId: string,
role: unknown,
isMatch: (message: T) => boolean = (message) => String(message.id || '') === messageId,
): T[] {
const index = messages.findIndex(isMatch)
if (index < 0) {
return messages
}
if (role === 'user') {
return messages.slice(0, index)
}
return messages.slice(0, index + 1)
}
export interface RewindCandidateMessage {
id?: unknown
role?: unknown
is_completed?: unknown
}
export function resolveRewindAffordance(
messages: RewindCandidateMessage[],
messageId: string,
opts: { embeddedMode?: boolean; outgoingWork?: boolean } = {},
): { canRewind: boolean } {
return { canRewind: rewindableMessageIds(messages, opts).has(messageId) }
}
/**
* The ids a rewind control may be offered on, resolved in one pass.
*
* The transcript asks this per rendered message and re-asks on every streamed
* token, so the whole-list conditions (is any turn still generating?) are
* hoisted out of the per-message check instead of rescanning for each row.
*/
export function rewindableMessageIds(
messages: RewindCandidateMessage[],
opts: { embeddedMode?: boolean; outgoingWork?: boolean } = {},
): Set<string> {
const ids = new Set<string>()
if (opts.embeddedMode || opts.outgoingWork) {
return ids
}
let tail: { id: string; role: unknown } | null = null
for (const message of messages) {
if (message.role === 'assistant' && message.is_completed === false) {
return new Set<string>()
}
const id = String(message.id || '')
if (id && (message.role === 'assistant' || message.role === 'user')) {
ids.add(id)
tail = { id, role: message.role }
}
}
// Rewinding to the newest answer would delete nothing.
if (tail?.role === 'assistant') {
ids.delete(tail.id)
}
return ids
}
export function rewindHttpConflictCode(err: unknown): string {
if (!err || typeof err !== 'object') {
return ''
}
const rec = err as { code?: unknown; status?: unknown; $httpStatus?: unknown }
const status = rec.status ?? rec.$httpStatus
if (status !== 409) {
return ''
}
return typeof rec.code === 'string' ? rec.code : ''
}
export function rewindConflictI18nKey(code: string): string {
if (code === 'REWIND_NO_CHECKPOINT') {
return 'chat.rewind.noCheckpoint'
}
if (code === 'REWIND_SANDBOX_REPLACED') {
return 'chat.rewind.sandboxReplaced'
}
return 'chat.rewind.busy'
}
@@ -0,0 +1,70 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { runInNewContext } from 'node:vm'
import test from 'node:test'
import { effectScope, reactive, ref, watch } from 'vue'
import { createSessionActivityState, type SessionActivity } from '../../stores/sessionActivityState'
const source = readFileSync(new URL('./index.vue', import.meta.url), 'utf8')
const start = source.indexOf('watch([activitySessionId,')
const end = source.indexOf('const historyLoading =', start)
assert.ok(start > 0 && end > start)
function fixture() {
const entries = reactive<Record<string, SessionActivity>>({})
const sessionActivity = createSessionActivityState(entries, async () => [])
const refs = {
activitySessionId: ref('session-a'), isReplying: ref(false), isStreaming: ref(false),
isImRecovering: ref(false), currentAssistantMessageId: ref('reply-a'),
}
const scope = effectScope()
scope.run(() => runInNewContext(source.slice(start, end), { ...refs, sessionActivity, watch, props: { embeddedMode: false } }))
return { ...refs, entries, sessionActivity, close: () => scope.stop() }
}
test('a terminal reply clears the sidebar even while its SSE connection remains open', () => {
const f = fixture()
try {
f.isReplying.value = true
f.isStreaming.value = true
assert.ok(f.entries['session-a'])
f.isReplying.value = false
f.currentAssistantMessageId.value = ''
assert.equal(f.entries['session-a'], undefined)
f.isStreaming.value = false
f.isStreaming.value = true
assert.equal(f.entries['session-a'], undefined, 'transport changes cannot restart the turn indicator')
} finally { f.close() }
})
test('generation remains active during connection setup and IM recovery', () => {
const f = fixture()
try {
f.isReplying.value = true
assert.ok(f.entries['session-a'], 'waiting for headers still counts as generating')
f.isReplying.value = false
f.isImRecovering.value = true
assert.ok(f.entries['session-a'], 'IM polling counts as active without an SSE connection')
f.isImRecovering.value = false
assert.equal(f.entries['session-a'], undefined)
} finally { f.close() }
})
test('stopping the current conversation does not clear a detached conversation', () => {
const f = fixture()
try {
f.isReplying.value = true
f.sessionActivity.detach('session-a')
f.activitySessionId.value = ''
f.isReplying.value = false
assert.equal(f.entries['session-a']?.detached, true)
f.activitySessionId.value = 'session-b'
f.isReplying.value = true
f.isStreaming.value = true
f.isReplying.value = false
assert.equal(f.entries['session-b'], undefined)
assert.ok(f.entries['session-a'])
f.isReplying.value = true
assert.ok(f.entries['session-b'], 'a new turn starts the indicator again')
} finally { f.close() }
})
@@ -0,0 +1,182 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const source = readFileSync(new URL('./index.vue', import.meta.url), 'utf8')
const steerApi = readFileSync(new URL('../../api/chat/steer.ts', import.meta.url), 'utf8')
function attachSteerFollowUpSource() {
const start = source.indexOf('const attachSteerFollowUp = async')
const end = source.indexOf('const sendMsg = async', start)
assert.notEqual(start, -1)
assert.notEqual(end, -1)
return source.slice(start, end)
}
test('refresh restores the overlay queue from the live run', () => {
assert.match(steerApi, /export async function listSteerSession/)
assert.match(source, /listSteerSession/)
assert.match(source, /hydrateSteerQueue/)
assert.match(source, /if \(!steerQueue\.value\.length\)/)
})
// A turn that absorbed a mid-run message is split into several assistant
// segments, and every segment after the first gets a synthetic id. Resuming
// or stopping with that id hits a row the server has never heard of: the
// stream 404s and the UI looks like the agent died on refresh.
test('resume and stop address the persisted assistant id, not a fork id', () => {
const fork = readFileSync(new URL('../../utils/steerStreamFork.ts', import.meta.url), 'utf8')
assert.match(fork, /export function persistedAssistantId/)
const start = source.indexOf('onAfterMsgList: async ()')
const end = source.indexOf('onAgentQuery:', start)
assert.notEqual(start, -1)
assert.notEqual(end, -1)
const hook = source.slice(start, end)
assert.match(hook, /persistedAssistantId\(lastMessage\)/)
assert.match(hook, /currentAssistantMessageId\.value = resumeId/)
assert.match(hook, /query: resumeId/)
assert.doesNotMatch(hook, /query: lastMessage\.id/)
// An injected user row can be the last entry in the list. Keying the resume
// off the tail row would then skip continue-stream and the still-running
// agent would produce nothing visible.
assert.match(hook, /findLastMessage\(\s*\(message\) => message\.role === 'assistant' && !message\.is_completed\s*\)/)
assert.doesNotMatch(hook, /messagesList\[messagesList\.length - 1\]/)
})
// Stopping means stopping. Firing off the queued messages as a fresh run is
// the opposite of what the button says. The overlay stays until /stop
// succeeds, so a failed request can restore the composer without losing chips.
test('stop clears the queue only after the stop API succeeds', () => {
const start = source.indexOf('const handleStopGeneration = ')
const confirmedStart = source.indexOf('const handleStopConfirmed = ')
const failedStart = source.indexOf('const handleStopFailed = ')
const end = source.indexOf('const dropSteerQueueItem', start)
assert.notEqual(start, -1)
assert.notEqual(confirmedStart, -1)
assert.notEqual(failedStart, -1)
assert.notEqual(end, -1)
const gen = source.slice(start, confirmedStart)
assert.doesNotMatch(gen, /steerQueue\.value = \[\]/)
assert.doesNotMatch(gen, /attachSteerFollowUp/)
const confirmed = source.slice(confirmedStart, failedStart)
assert.match(confirmed, /steerQueue\.value = \[\]/)
const failed = source.slice(failedStart, end)
assert.match(failed, /isReplying\.value = true/)
})
// Matching queued text against the message list attaches the wrong bubble as
// soon as the user sends the same thing twice. The follow-up run persists its
// query under its own request_id, which identifies the rows exactly.
test('follow-up attaches persisted users by request_id', () => {
const fn = attachSteerFollowUpSource()
assert.match(fn, /persisted\.request_id !== newAssistant\.request_id/)
assert.match(fn, /hydrateSteerQueue\(\{ onlyWhenLive: true \}\)/)
assert.doesNotMatch(fn, /m\.content === q\.content/)
})
// A 503 from the steer lookup must toast, not fall through to sendMsg. Only
// an explicit new_run (no live turn) starts a normal AgentQA.
test('steer lookup failure does not start a second turn', () => {
const start = source.indexOf('const handleSteerMsg = async')
const end = source.indexOf('const handleRetrySteer = async', start)
assert.notEqual(start, -1)
assert.notEqual(end, -1)
const fn = source.slice(start, end)
const newRun = fn.indexOf("if (res?.status === 'new_run')")
const catchIdx = fn.indexOf('} catch (e) {')
assert.notEqual(newRun, -1)
assert.notEqual(catchIdx, -1)
assert.ok(newRun < catchIdx, 'new_run fallback must sit in the try, not the catch')
const newRunBlock = fn.slice(newRun, catchIdx)
assert.match(newRunBlock, /awaitingIdleSend/)
assert.match(newRunBlock, /isReplying/)
assert.match(newRunBlock, /await sendMsg\(/)
assert.doesNotMatch(fn.slice(catchIdx), /sendMsg\(/)
})
test('new_run while a stream is live does not abort it', () => {
const start = source.indexOf('const handleSteerMsg = async')
const end = source.indexOf('const handleRetrySteer = async', start)
const fn = source.slice(start, end)
const newRun = fn.indexOf("if (res?.status === 'new_run')")
const catchIdx = fn.indexOf('} catch (e) {')
const block = fn.slice(newRun, catchIdx)
assert.match(block, /isStreaming/)
assert.doesNotMatch(block, /stopStream\(/)
})
test('turn complete flushes idle new_run sends before attaching a follow-up', () => {
assert.match(source, /const flushSteerAfterTurn = async/)
assert.match(source, /awaitingIdleSend/)
const start = source.indexOf('onTurnComplete:')
const end = source.indexOf('});', start)
const hook = source.slice(start, end)
assert.match(hook, /flushSteerAfterTurn\(persistedAssistantId\(message\)\)/)
assert.doesNotMatch(hook, /attachSteerFollowUp\(persistedAssistantId\(message\)\)/)
})
test('remaining overlay after-items chain after a follow-up stream ends', () => {
const fn = attachSteerFollowUpSource()
const finallyStart = fn.indexOf('} finally {')
assert.notEqual(finallyStart, -1, 'attachSteerFollowUp must have a finally block')
const finallyBlock = fn.slice(finallyStart)
// startStream awaits the whole SSE. The follow-up's onTurnComplete therefore
// runs while attachingSteerFollowUp is still true and would no-op. Remaining
// after-items have to be retried once that guard drops.
assert.match(finallyBlock, /steerQueue\.value\.some\(item => !item\.failed\)/)
assert.match(finallyBlock, /void attachSteerFollowUp\(/)
})
// Switching sessions while the follow-up poll is in flight used to keep
// using session_id.value, so continue-stream landed on the new chat.
test('follow-up attach aborts when the session changes', () => {
const fn = attachSteerFollowUpSource()
assert.match(fn, /const sessionId = session_id\.value/)
assert.match(fn, /session_id\.value !== sessionId/)
assert.match(fn, /getMessageList\(\{ session_id: sessionId/)
assert.match(fn, /session_id: sessionId/)
})
// After a mid-run inject the completing bubble is a steer-cont-* segment.
// Passing that id into attachSteerFollowUp cannot exclude the persisted
// row, so the finishing turn was picked as the follow-up.
test('follow-up attach keys off the persisted assistant id, not a fork id', () => {
const start = source.indexOf('onTurnComplete:')
const end = source.indexOf('});', start)
assert.notEqual(start, -1)
assert.notEqual(end, -1)
const hook = source.slice(start, end)
assert.match(hook, /flushSteerAfterTurn\(persistedAssistantId\(message\)\)/)
assert.doesNotMatch(hook, /attachSteerFollowUp\(message\?\.id\)/)
const flushStart = source.indexOf('const flushSteerAfterTurn = async')
const flushEnd = source.indexOf('const attachSteerFollowUp = async', flushStart)
assert.match(source.slice(flushStart, flushEnd), /attachSteerFollowUp\(completedAssistantId\)/)
})
// A stop that arrives over SSE (other tab, /stop API) discards the server
// queue. The overlay has to drop too, not only the local Stop button.
test('remove drops overlay when the server already injected the item', () => {
const start = source.indexOf('const handleRemoveSteer = async')
const end = source.indexOf('let attachingSteerFollowUp', start)
assert.notEqual(start, -1)
assert.notEqual(end, -1)
const fn = source.slice(start, end)
assert.match(fn, /already_injected/)
assert.match(fn, /dropSteerQueueItem\(steerId\)/)
assert.match(fn, /removed === false/)
})
test('remote stop clears the overlay queue', () => {
assert.match(source, /onGenerationStopped/)
const start = source.indexOf('onGenerationStopped')
assert.notEqual(start, -1)
const snippet = source.slice(start, start + 180)
assert.match(snippet, /steerQueue\.value = \[\]/)
})
@@ -0,0 +1,170 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { webcrypto } from 'node:crypto'
import vm from 'node:vm'
import test from 'node:test'
import { makeSteerClientId } from '../../utils/steerId.ts'
import ts from 'typescript'
import { reactive } from 'vue'
import { previewSteerMessage, discardSteerPreview, forkAfterInjectedUser, reconcileSteerMessageId, persistedAssistantId } from '../../utils/steerStreamFork.ts'
const source = readFileSync(new URL('./index.vue', import.meta.url), 'utf8')
const handlers = source.slice(source.indexOf('const dropSteerQueueItem ='), source.indexOf('let attachingSteerFollowUp ='))
const deferred = () => {
let resolve, reject
const promise = new Promise((yes, no) => { resolve = yes; reject = no })
return { promise, resolve, reject }
}
function harness(overrides = {}) {
const state = {
session_id: { value: 'session' }, currentAssistantMessageId: { value: 'assistant' },
isReplying: { value: true }, isStreaming: { value: true },
composerLocked: { value: false },
steerQueue: { value: [] }, messagesList: reactive([]), crypto: webcrypto, makeSteerClientId,
previewSteerMessage, discardSteerPreview, reconcileSteerMessageId,
scrollToBottom() {}, sendMsg() { throw new Error('must not start a second run') },
MessagePlugin: { info() {}, error() {} }, t: key => key,
console: { error() {} }, ...overrides,
}
const actions = vm.runInNewContext(`${handlers}\n({ handleSteerMsg, handlePromoteSteer, handleRetrySteer, handleRemoveSteer })`, state)
return { ...actions, state }
}
test('locked composer drops a steer without touching the queue', async () => {
let called = 0
const h = harness({
composerLocked: { value: true },
steerSession: async () => { called += 1; return { status: 'queued' } },
})
await h.handleSteerMsg('queued')
assert.equal(called, 0)
assert.equal(h.state.steerQueue.value.length, 0)
})
test('default after stays below; promotion immediately moves it into the transcript', async () => {
const request = deferred(), promote = deferred()
const h = harness({ steerSession: () => request.promise, promoteSteerSession: () => promote.promise })
const sending = h.handleSteerMsg('queued')
const item = h.state.steerQueue.value[0]
assert.equal(item.delivery, 'after')
assert.equal(h.state.messagesList.length, 0)
request.resolve({ status: 'queued', steer_id: item.steer_id })
await sending
const promoting = h.handlePromoteSteer(item.steer_id)
assert.equal(item.delivery, 'inject')
assert.equal(h.state.steerQueue.value.filter(q => q.delivery === 'after').length, 0)
assert.equal(h.state.messagesList[0].content, 'queued')
promote.resolve({ status: 'queued' })
await promoting
})
test('direct inject shows immediately and an early SSE receipt does not duplicate it', async () => {
const request = deferred()
const h = harness({ steerSession: () => request.promise })
const assistant = { id: 'assistant', role: 'assistant', request_id: 'request', is_completed: false }
h.state.messagesList.push(assistant)
const sending = h.handleSteerMsg('补充', [], 'inject')
const item = h.state.steerQueue.value[0]
assert.equal(h.state.messagesList[1].content, '补充')
forkAfterInjectedUser(h.state.messagesList, assistant, h.state.messagesList[1], item.steer_id)
h.state.steerQueue.value.splice(0, 1) // onUserMessageInjected receipt
request.resolve({ status: 'queued', steer_id: item.steer_id })
await sending
assert.equal(h.state.messagesList.filter(m => m.role === 'user').length, 1)
assert.equal(h.state.steerQueue.value.length, 0)
})
test('failed inject retries with the same ID and bubble', async () => {
const ids = []
const h = harness({ steerSession: async (...args) => {
ids.push(args[5])
if (ids.length === 1) throw new Error('network')
return { status: 'queued', steer_id: args[5] }
} })
await h.handleSteerMsg('补充', [], 'inject')
assert.equal(h.state.messagesList[0]._steerFailed, true)
await h.handleRetrySteer(ids[0])
assert.deepEqual(ids, [ids[0], ids[0]])
assert.equal(h.state.messagesList.length, 1)
assert.equal(h.state.messagesList[0]._steerFailed, undefined)
})
test('a lost HTTP response after a delivery receipt does not report a failed send', async () => {
const request = deferred(), errors = []
const h = harness({ steerSession: () => request.promise, MessagePlugin: { info() {}, error: message => errors.push(message) } })
const sending = h.handleSteerMsg('补充', [], 'inject')
h.state.steerQueue.value.splice(0, 1) // receipt already removed the item
request.reject(new Error('response lost'))
await sending
assert.equal(errors.length, 0)
})
test('failed promotion restores the after queue and removes only its optimistic row', async () => {
const h = harness({ promoteSteerSession: async () => { throw new Error('network') } })
h.state.steerQueue.value.push({ steer_id: 'queued', content: '补充', delivery: 'after' })
await h.handlePromoteSteer('queued')
assert.equal(h.state.steerQueue.value[0].delivery, 'after')
assert.equal(h.state.messagesList.length, 0)
})
const streamSource = readFileSync(new URL('../../composables/useChatStreamHandler.ts', import.meta.url), 'utf8')
const receiptStart = streamSource.indexOf("case 'user_message_injected': {")
const receiptEnd = streamSource.indexOf("case 'complete':", receiptStart)
assert.ok(receiptStart >= 0 && receiptEnd > receiptStart)
const consolidation = streamSource.slice(streamSource.indexOf('const consolidateCollaborationStatus ='), streamSource.indexOf('const reconstructEventStreamFromSteps ='))
const receipt = ts.transpile(`() => { ${consolidation}
switch ('user_message_injected') {
${streamSource.slice(receiptStart, receiptEnd)}
} }`)
function receiveInjection(h, steerId, userId) {
vm.runInNewContext(receipt, {
messagesList: h.state.messagesList,
message: h.state.messagesList.findLast(m => m.role === 'assistant'),
dataPayload: { steer_id: steerId, user_message_id: userId, content: '写到Docx' },
data: {}, dataId: 'request', replaySegments: new Map(),
forkAfterInjectedUser, persistedAssistantId, log() {}, emitMessageCreated() {}, onAgentChunkBound() {},
onUserMessageInjected(id) {
const index = h.state.steerQueue.value.findIndex(item => item.steer_id === id)
if (index >= 0) h.state.steerQueue.value.splice(index, 1)
},
})()
}
for (const receiptFirst of [false, true]) {
test(`server-assigned steer ID reconciles the optimistic bubble when SSE arrives ${receiptFirst ? 'before' : 'after'} HTTP`, async () => {
const request = deferred()
const h = harness({ steerSession: () => request.promise })
h.state.messagesList.push({ id: 'assistant', role: 'assistant', request_id: 'request', is_completed: false })
const sending = h.handleSteerMsg('写到Docx', [{ id: 'mention' }], 'inject')
if (receiptFirst) receiveInjection(h, 'server-steer', 'persisted-user')
request.resolve({ status: 'queued', steer_id: 'server-steer' })
await sending
if (!receiptFirst) receiveInjection(h, 'server-steer', 'persisted-user')
const users = h.state.messagesList.filter(m => m.role === 'user')
assert.equal(users.length, 1)
assert.equal(users[0].id, 'persisted-user')
assert.equal(users[0]._steerPending, undefined)
assert.equal(users[0].mentioned_items[0].id, 'mention')
assert.equal(h.state.steerQueue.value.length, 0)
assert.deepEqual(h.state.messagesList.map(m => m.role), ['assistant', 'user', 'assistant'])
})
}
test('concurrent identical injects reconcile by their HTTP receipts without merging distinct messages', async () => {
const first = deferred(), second = deferred()
let calls = 0
const h = harness({ steerSession: () => (++calls === 1 ? first.promise : second.promise) })
h.state.messagesList.push({ id: 'assistant', role: 'assistant', request_id: 'request', is_completed: false })
const sendingFirst = h.handleSteerMsg('写到Docx', [{ id: 'first' }], 'inject')
const sendingSecond = h.handleSteerMsg('写到Docx', [{ id: 'second' }], 'inject')
receiveInjection(h, 'server-first', 'user-first')
receiveInjection(h, 'server-second', 'user-second')
second.resolve({ status: 'queued', steer_id: 'server-second' })
await sendingSecond
first.resolve({ status: 'queued', steer_id: 'server-first' })
await sendingFirst
const users = h.state.messagesList.filter(m => m.role === 'user')
assert.deepEqual(users.map(m => [m.id, m.mentioned_items[0].id]), [['user-first', 'first'], ['user-second', 'second']])
assert.equal(h.state.steerQueue.value.length, 0)
})