chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,259 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import { effectScope, nextTick, ref, watch } from 'vue'
|
||||
|
||||
const source = readFileSync(new URL('./AgentEditorModal.vue', import.meta.url), 'utf8')
|
||||
|
||||
test('editing an agent closes the editor after a successful save', () => {
|
||||
assert.match(
|
||||
source,
|
||||
/await updateAgent\(formData\.value\.id, payload\);\s*MessagePlugin\.success\(t\('agent\.messages\.updated'\)\);\s*emit\('success'\);\s*handleClose\(\);/
|
||||
)
|
||||
})
|
||||
|
||||
test('the first successful create stays open for integration setup', () => {
|
||||
const createBranch = source.match(
|
||||
/if \(editorMode\.value === 'create'\) \{([\s\S]*?)^\s{4}\} else \{/m
|
||||
)?.[1]
|
||||
|
||||
assert.ok(createBranch, 'expected to find the create branch')
|
||||
assert.doesNotMatch(createBranch, /handleClose\(\)/)
|
||||
assert.match(createBranch, /savedAgent\.value = created;/)
|
||||
})
|
||||
|
||||
test('save button labels distinguish create from save-and-close', () => {
|
||||
assert.match(
|
||||
source,
|
||||
/const saveButtonLabel = computed\(\(\) =>\s*editorMode\.value === 'create'\s*\? t\('agent\.editor\.buttons\.create'\)\s*: t\('agent\.editor\.buttons\.saveAndClose'\)\s*\)/
|
||||
)
|
||||
assert.match(source, /saveButtonLabel/)
|
||||
})
|
||||
|
||||
test('shows a post-create hint after the first successful save', () => {
|
||||
assert.match(source, /const isPostCreateSession = computed\(\(\) => !!savedAgent\.value\)/)
|
||||
assert.match(source, /settings-footer-note/)
|
||||
assert.match(source, /agent\.editor\.postCreateHint\.title/)
|
||||
})
|
||||
|
||||
// Locate a settings row by the i18n key of its label and return the attributes
|
||||
// that sit before class="setting-row" — i.e. whatever v-if guards that row.
|
||||
// Anchoring on the label keeps these assertions stable across reformatting.
|
||||
function settingRowGuard(labelKey) {
|
||||
const key = labelKey.replace(/\./g, '\\.')
|
||||
const row = source.match(
|
||||
new RegExp(
|
||||
`<div([^>]*)class="setting-row">\\s*<div class="setting-info">\\s*<label>\\{\\{ \\$t\\('${key}'\\) \\}\\}`
|
||||
)
|
||||
)
|
||||
assert.ok(row, `expected to find the ${labelKey} row`)
|
||||
return row[1]
|
||||
}
|
||||
|
||||
test('conversation settings stay reachable in smart-reasoning mode', () => {
|
||||
// Agent mode keeps the section: it explains that history follows the context
|
||||
// window and hosts retain_retrieval_history, so it must not be gated on mode.
|
||||
assert.match(source, /v-show="currentSection === 'conversation'"/)
|
||||
assert.doesNotMatch(source, /currentSection === 'conversation' && !isAgentMode/)
|
||||
|
||||
// The nav entry is pushed unconditionally; a re-introduced guard would indent it.
|
||||
const navItems = source.match(/const navItems = computed\(\(\) => \{([\s\S]*?)^\}\);/m)?.[1]
|
||||
assert.ok(navItems, 'expected to find the nav items computed')
|
||||
assert.match(navItems, /^ items\.push\(\{ key: 'conversation'/m)
|
||||
|
||||
// Switching to agent mode must not evict the user from the section.
|
||||
// Tolerates the watch being dropped entirely by a later cleanup.
|
||||
const modeWatch = source.match(/watch\(isAgentMode, \(isAgent\) => \{([\s\S]*?)^\}\);/m)?.[1] ?? ''
|
||||
assert.doesNotMatch(modeWatch, /conversation/)
|
||||
})
|
||||
|
||||
test('history turns stays hidden in smart-reasoning mode', () => {
|
||||
// The agent path sizes history by the context window and never reads
|
||||
// history_turns (session_agent_qa.go -> LoadAgentHistory), so an input there
|
||||
// would change nothing. KnowledgeQA still caps its history by it.
|
||||
const guard = settingRowGuard('agent.editor.historyTurns')
|
||||
assert.match(guard, /v-if="!isAgentMode && formData\.config\.multi_turn_enabled"/)
|
||||
})
|
||||
|
||||
test('multi-turn switch stays hidden in smart-reasoning mode', () => {
|
||||
// CustomAgent.EnsureDefaults pins MultiTurnEnabled to true for smart-reasoning,
|
||||
// so an editable switch would silently revert after save.
|
||||
const guard = settingRowGuard('agent.editor.multiTurn')
|
||||
assert.match(guard, /v-if="!isAgentMode"/)
|
||||
})
|
||||
|
||||
test('query rewrite stays hidden in smart-reasoning mode', () => {
|
||||
// enable_rewrite is consumed by the KnowledgeQA pipeline only.
|
||||
const guard = settingRowGuard('agent.editor.enableRewrite')
|
||||
assert.match(guard, /!isAgentMode/)
|
||||
})
|
||||
|
||||
test('the section description matches what the mode actually shows', () => {
|
||||
// The default copy mentions query rewriting, which agent mode does not show.
|
||||
assert.match(source, /isAgentMode\.value\s*\?\s*t\('agentEditor\.desc\.conversationSectionAgent'\)/)
|
||||
assert.match(source, /<p class="section-description">\{\{ conversationSectionDesc \}\}<\/p>/)
|
||||
})
|
||||
|
||||
test('history turns can be raised beyond the old 20 cap', () => {
|
||||
// KnowledgeQA history is capped by turns alone; 20 was too tight for the
|
||||
// windows current models have.
|
||||
const input = source.match(/<t-input-number v-model="formData\.config\.history_turns"[^>]*>/)
|
||||
assert.ok(input, 'expected to find the history turns input')
|
||||
assert.match(input[0], /:max="100"/)
|
||||
})
|
||||
|
||||
test('retrieval retention is offered to agents that actually have a knowledge base', () => {
|
||||
// retain_retrieval_history is read only by the agent path
|
||||
// (internal/agent/observe.go) and only rewrites KB/Wiki tool results, so it
|
||||
// is meaningless without a knowledge base.
|
||||
const guard = settingRowGuard('agent.editor.retainRetrievalHistory')
|
||||
assert.match(guard, /isAgentMode && hasKnowledgeBase/)
|
||||
})
|
||||
|
||||
test('skills and sandbox share one editor section', () => {
|
||||
const navItems = source.match(/const navItems = computed\(\(\) => \{([\s\S]*?)^\}\);/m)?.[1]
|
||||
assert.ok(navItems, 'expected to find the nav items computed')
|
||||
assert.match(navItems, /key: 'skills'/)
|
||||
assert.match(navItems, /icon: SKILL_ICON/)
|
||||
assert.doesNotMatch(navItems, /key: 'sandbox'/)
|
||||
|
||||
const capabilityGroup = source.match(/pickItems\(\['multimodal', 'tools', 'mcp', 'skills'\]\)/)
|
||||
assert.ok(capabilityGroup, 'expected the capability group to list skills without a separate sandbox tab')
|
||||
|
||||
assert.match(source, /v-show="currentSection === 'skills' && isAgentMode"/)
|
||||
assert.doesNotMatch(source, /currentSection === 'sandbox' && isAgentMode/)
|
||||
assert.match(source, /sandbox: 'skills'/)
|
||||
assert.match(source, /formData\.config\.sandbox_config_id/)
|
||||
assert.match(source, /:disabled="!canEnableSkills"/)
|
||||
assert.match(source, /sandbox-option/)
|
||||
assert.doesNotMatch(source, /skill-info-box/)
|
||||
})
|
||||
|
||||
test('agent skill picker uses the catalog and only enables ready installs', () => {
|
||||
assert.match(source, /function autoBindSoleSandbox\(/)
|
||||
assert.match(source, /canEnableSkills/)
|
||||
assert.match(source, /catalogSkillRows/)
|
||||
assert.match(source, /showCatalogSkillList/)
|
||||
assert.match(source, /skillsSelectionMode\.value !== 'none'/)
|
||||
assert.match(source, /:disabled="!skill\.selectable"/)
|
||||
assert.match(source, /catalogSkillGroups/)
|
||||
assert.match(source, /installPartial/)
|
||||
assert.match(source, /installCatalogToCurrent/)
|
||||
assert.match(source, /agent\.editor\.installToThisSandbox/)
|
||||
assert.match(source, /skill-pick-list/)
|
||||
assert.match(source, /skill-pick-group/)
|
||||
assert.match(source, /skill-pick__badge/)
|
||||
assert.match(source, /skillStatusIcon/)
|
||||
assert.match(source, /isSkillBusy/)
|
||||
assert.match(source, /viewInstallProgress/)
|
||||
assert.match(source, /openSkillInstallProgress/)
|
||||
assert.doesNotMatch(source, /await openSkillInstallProgress\(skill\)/)
|
||||
assert.match(source, /SandboxSkillsPanel/)
|
||||
assert.match(source, /focus-skill-id/)
|
||||
assert.match(source, /skillsGroupUnavailable/)
|
||||
assert.match(source, /selectedSandboxSummary/)
|
||||
assert.match(source, /line-clamp: 2/)
|
||||
assert.doesNotMatch(source, /skillsSelectionMode === 'selected' && catalogSkillRows/)
|
||||
assert.doesNotMatch(source, /skill-list-summary/)
|
||||
assert.doesNotMatch(source, /skill-ready-stat/)
|
||||
})
|
||||
|
||||
test('agent skill picker offers upgrades to admins only and keeps upgrading skills selected', () => {
|
||||
assert.match(source, /from '@\/utils\/skillUpgrade'/)
|
||||
assert.match(source, /const upgradable = Boolean\(inst && installUpgradable\(item, inst\)\)/)
|
||||
assert.match(source, /canInstallSkills\.value && hasSandboxSelected\.value && skill\.upgradable/)
|
||||
assert.match(source, /v-if="canUpgradeSkillRow\(skill\)"/)
|
||||
assert.match(source, /v-else-if="canUpgradeSkillRow\(skill\)"/)
|
||||
assert.match(source, /agent\.editor\.upgradeOnThisSandbox/)
|
||||
// The progress drawer reads admin-only endpoints, so it is not offered to others.
|
||||
assert.match(source, /v-else-if="canInstallSkills && isSkillBusy\(skill\)"/)
|
||||
assert.match(source, /skill\.selectable \|\| \(skill\.installed && isSkillBusy\(skill\)\)/)
|
||||
})
|
||||
|
||||
test('a skill whose previous version still runs stays selectable during and after an upgrade', () => {
|
||||
assert.match(source, /installEnabled && \(installStatus === 'ready' \|\| Boolean\(servedNote\)\)/)
|
||||
assert.match(source, /v-if="skill\.selectable && skill\.servedNote"/)
|
||||
// Installing the catalog version over a failed upgrade is the upgrade retried.
|
||||
assert.match(source, /installsAnUpgrade\(skill\) \? \$t\('settings\.skills\.upgrade'\) : \$t\('agent\.editor\.installShort'\)/)
|
||||
assert.match(source, /return skill\.upgradable \|\| Boolean\(skill\.servedNote\)/)
|
||||
})
|
||||
|
||||
test('retrieval strategy settings are hidden in agent mode, where search_knowledge ignores them', () => {
|
||||
// search_knowledge reads the global retrieval configuration; showing the
|
||||
// per-agent thresholds in agent mode let users tune values with no effect.
|
||||
assert.match(source, /v-show="currentSection === 'retrieval' && hasKnowledgeBase && !isAgentMode"/)
|
||||
assert.match(source, /if \(hasKnowledgeBase\.value && !isAgentMode\.value\) \{\s*items\.push\(\{ key: 'retrieval'/)
|
||||
const modeWatch = source.match(/watch\(isAgentMode, \(isAgent\) => \{([\s\S]*?)^\}\);/m)?.[1] ?? ''
|
||||
assert.match(modeWatch, /isAgent && \([^)]*currentSection\.value === 'retrieval'/)
|
||||
})
|
||||
|
||||
async function mcpFixture(t, config) {
|
||||
const init = source.match(/const initMcpSelectionMode = \(\) => \{[\s\S]*?^\};/m)?.[0]
|
||||
const start = source.indexOf('watch(mcpSelectionMode,')
|
||||
const end = source.indexOf('watch(() => formData.value.config.sandbox_config_id', start)
|
||||
assert.ok(init && start >= 0 && end > start, 'expected MCP initialization and watchers')
|
||||
const state = {
|
||||
watch,
|
||||
formData: ref({ config: { mcp_selection_mode: 'none', mcp_services: [] } }),
|
||||
loadedConfig: structuredClone(config),
|
||||
mcpSelectionMode: ref('none'),
|
||||
isInitializing: ref(true),
|
||||
}
|
||||
const scope = effectScope()
|
||||
t.after(() => scope.stop())
|
||||
// Run the component's actual initialization and watchers with Vue's scheduler.
|
||||
scope.run(() => runInNewContext(`${source.slice(start, end)}\n${init}\nformData.value = { config: loadedConfig };\ninitMcpSelectionMode();`, state))
|
||||
await nextTick(() => { state.isInitializing.value = false })
|
||||
return state
|
||||
}
|
||||
|
||||
test('legacy empty MCP config opens as all without rewriting persisted config', async t => {
|
||||
const config = { mcp_selection_mode: '', mcp_services: [] }
|
||||
const state = await mcpFixture(t, config)
|
||||
assert.equal(state.mcpSelectionMode.value, 'all')
|
||||
assert.deepEqual(state.formData.value.config, config)
|
||||
})
|
||||
|
||||
test('MCP hydration preserves saved modes and legacy service lists', async t => {
|
||||
for (const mode of ['', 'none', 'selected', 'all']) {
|
||||
const config = { mcp_selection_mode: mode, mcp_services: ['service-a'] }
|
||||
const state = await mcpFixture(t, config)
|
||||
assert.equal(state.mcpSelectionMode.value, mode || 'selected')
|
||||
assert.deepEqual(state.formData.value.config, config)
|
||||
}
|
||||
})
|
||||
|
||||
test('editing a legacy service list persists selected mode without toggling the radio', async t => {
|
||||
const state = await mcpFixture(t, { mcp_selection_mode: '', mcp_services: ['service-a'] })
|
||||
assert.equal(state.mcpSelectionMode.value, 'selected')
|
||||
// t-select replaces the v-model array while leaving the radio unchanged.
|
||||
state.formData.value.config.mcp_services = ['service-b']
|
||||
await nextTick()
|
||||
assert.deepEqual(state.formData.value.config, {
|
||||
mcp_selection_mode: 'selected', mcp_services: ['service-b'],
|
||||
})
|
||||
})
|
||||
|
||||
test('clearing a legacy service list persists selected with no services', async t => {
|
||||
const state = await mcpFixture(t, { mcp_selection_mode: '', mcp_services: ['service-a'] })
|
||||
state.formData.value.config.mcp_services.splice(0)
|
||||
await nextTick()
|
||||
assert.equal(state.formData.value.config.mcp_selection_mode, 'selected')
|
||||
assert.deepEqual(state.formData.value.config.mcp_services, [])
|
||||
})
|
||||
|
||||
test('switching MCP modes still clears lists only for all and none', async t => {
|
||||
const state = await mcpFixture(t, { mcp_selection_mode: '', mcp_services: ['service-a'] })
|
||||
for (const mode of ['all', 'selected', 'none']) {
|
||||
state.mcpSelectionMode.value = mode
|
||||
await nextTick()
|
||||
assert.equal(state.formData.value.config.mcp_selection_mode, mode)
|
||||
assert.equal(state.formData.value.config.mcp_services.length, 0)
|
||||
if (mode === 'selected') {
|
||||
state.formData.value.config.mcp_services = ['service-b']
|
||||
await nextTick()
|
||||
assert.deepEqual(state.formData.value.config.mcp_services, ['service-b'])
|
||||
}
|
||||
}
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,55 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import test from 'node:test'
|
||||
import * as vue from 'vue'
|
||||
import ts from 'typescript'
|
||||
|
||||
test('the editor publishes existing local agents and retracts on create, close and unmount', async () => {
|
||||
const source = readFileSync(new URL('./AgentList.vue', import.meta.url), 'utf8')
|
||||
const publisher = source.match(/useAssistantPageContext\(\(\) => \{[\s\S]*?\n\}\)/)?.[0]
|
||||
assert.ok(publisher)
|
||||
const composable = readFileSync(new URL('../../composables/useAssistantPageContext.ts', import.meta.url), 'utf8')
|
||||
let context: unknown = null
|
||||
let unmount!: () => void
|
||||
const exports: any = {}
|
||||
runInNewContext(ts.transpileModule(composable, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS },
|
||||
}).outputText, { exports, require: (name: string) => name === 'vue'
|
||||
? { ...vue, onBeforeUnmount: (fn: () => void) => { unmount = fn } }
|
||||
: { useAssistantStore: () => ({
|
||||
publishPageContext: (_: symbol, value: unknown) => { context = value },
|
||||
retractPageContext: () => { context = null },
|
||||
}) },
|
||||
})
|
||||
const agent = { id: 'local', tenant_id: 1, name: 'Local' }
|
||||
const state = {
|
||||
editorVisible: vue.ref(false), editorMode: vue.ref('edit'),
|
||||
editingAgent: vue.ref<any>(agent), agents: vue.ref([agent]),
|
||||
useAssistantPageContext: exports.useAssistantPageContext,
|
||||
}
|
||||
const scope = vue.effectScope()
|
||||
scope.run(() => runInNewContext(publisher, state))
|
||||
try {
|
||||
assert.equal(context, null)
|
||||
state.editorVisible.value = true
|
||||
await vue.nextTick()
|
||||
assert.equal(JSON.stringify(context), JSON.stringify({ page: 'agent_editor', agentId: 'local', agentName: 'Local' }))
|
||||
state.editorVisible.value = false
|
||||
await vue.nextTick()
|
||||
assert.equal(context, null)
|
||||
state.editorVisible.value = true
|
||||
state.editorMode.value = 'create'
|
||||
await vue.nextTick()
|
||||
assert.equal(context, null)
|
||||
state.editorMode.value = 'edit'
|
||||
state.editingAgent.value = { ...agent, tenant_id: 2 }
|
||||
await vue.nextTick()
|
||||
assert.equal(context, null, 'shared agents, including builtin IDs, must not attach')
|
||||
state.editingAgent.value = agent
|
||||
await vue.nextTick()
|
||||
assert.ok(context)
|
||||
unmount()
|
||||
assert.equal(context, null)
|
||||
} finally { scope.stop() }
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test, { type TestContext } from 'node:test'
|
||||
import * as vue from 'vue'
|
||||
import * as sorting from '../../utils/resourceSorting.ts'
|
||||
import { change, fixture, flush } from '../../test-utils/vueFixture.ts'
|
||||
|
||||
function setup(t: TestContext) {
|
||||
const f = fixture(t)
|
||||
const fetchAgentsForList = t.mock.fn(async (_params: unknown, _force: boolean) => ({
|
||||
data: [{ id: 'agent', name: 'Updated agent' }], disabled_own_agent_ids: [],
|
||||
}))
|
||||
const page = f.component(new URL('./AgentList.vue', import.meta.url), {
|
||||
'vue-router': { useRoute: () => ({ query: {} }), useRouter: () => ({}) },
|
||||
'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
|
||||
'tdesign-vue-next': { MessagePlugin: {} },
|
||||
'@/stores/auth': { useAuthStore: () => ({ hasRole: () => true }) },
|
||||
'@/stores/ui': { useUIStore: () => ({}) },
|
||||
'@/stores/organization': { useOrganizationStore: () => ({
|
||||
sharedAgents: [], async fetchOrganizations() {}, async fetchSharedAgents() {},
|
||||
}) },
|
||||
'@/stores/chatResources': { useChatResourcesStore: () => ({ fetchAgentsForList }) },
|
||||
'@/stores/settings': { useSettingsStore: () => ({}) },
|
||||
'@/stores/menu': { useMenuStore: () => ({}) },
|
||||
'@/components/settings/useConfirmDelete': { useConfirmDelete: () => ({}) },
|
||||
'@/composables/useTenantModelReadiness': { useTenantModelReadiness: () => ({ loaded: vue.ref(true), isReadyForAgent: vue.ref(true) }) },
|
||||
'@/composables/useListUrlState': { useListUrlState: () => ({ scope: vue.ref('all'), creator: vue.ref('all'), query: vue.ref('') }) },
|
||||
'@/composables/useResourcePins': { useResourcePins: () => ({ favorites: vue.ref([]), recents: vue.ref([]) }) },
|
||||
'@/composables/useAssistantPageContext': { useAssistantPageContext() {} },
|
||||
'@/api/agent': {}, '@/api/chat/index': {}, '@/api/organization': {},
|
||||
'@/config/contextualGuides': {}, '@/config/settingsRoute': {},
|
||||
'@/utils/resourceListSearch': {}, '@/utils/card-list-badge': {}, '@/utils/resourceSorting': sorting,
|
||||
})
|
||||
return { ...f, ...page, fetchAgentsForList }
|
||||
}
|
||||
|
||||
test('refreshes the mounted agent list once per burst, ignoring other areas and unmounted pages', async t => {
|
||||
const f = setup(t)
|
||||
await flush()
|
||||
assert.equal(f.fetchAgentsForList.mock.callCount(), 1)
|
||||
f.fetchAgentsForList.mock.resetCalls()
|
||||
f.emit(change('knowledge.update'))
|
||||
t.mock.timers.tick(300)
|
||||
assert.equal(f.fetchAgentsForList.mock.callCount(), 0)
|
||||
f.emit(change('agent.create'))
|
||||
f.emit(change('agent.delete'))
|
||||
t.mock.timers.tick(300)
|
||||
await flush()
|
||||
assert.equal(f.fetchAgentsForList.mock.callCount(), 1)
|
||||
assert.equal(f.fetchAgentsForList.mock.calls[0].arguments[1], true)
|
||||
assert.equal(f.vm.agents[0].name, 'Updated agent')
|
||||
f.close()
|
||||
f.emit(change('agent.update'))
|
||||
t.mock.timers.tick(300)
|
||||
assert.equal(f.fetchAgentsForList.mock.callCount(), 1)
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,786 @@
|
||||
<template>
|
||||
<div class="artifact-library">
|
||||
<div class="header" style="--wails-draggable: drag">
|
||||
<div class="header-title" style="--wails-draggable: drag">
|
||||
<h2 style="--wails-draggable: drag">
|
||||
<ResourceIcon type="artifact" :size="24" />
|
||||
{{ $t('artifactLibrary.title') }}
|
||||
</h2>
|
||||
<p class="header-subtitle" style="--wails-draggable: drag">{{ $t('artifactLibrary.subtitle') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="toolbar">
|
||||
<div class="category-tabs" role="tablist" :aria-label="$t('artifactLibrary.typeFilter')">
|
||||
<button
|
||||
v-for="c in ARTIFACT_CATEGORIES"
|
||||
:key="c"
|
||||
type="button"
|
||||
role="tab"
|
||||
:aria-selected="category === c"
|
||||
@click="setCategory(c)"
|
||||
>
|
||||
{{ $t(`artifactLibrary.categories.${c}`) }}
|
||||
</button>
|
||||
</div>
|
||||
<t-input
|
||||
v-model="keyword"
|
||||
class="search-input"
|
||||
:placeholder="$t('artifactLibrary.searchPlaceholder')"
|
||||
:aria-label="$t('artifactLibrary.searchPlaceholder')"
|
||||
clearable
|
||||
>
|
||||
<template #prefix-icon><t-icon name="search" size="16px" /></template>
|
||||
</t-input>
|
||||
</div>
|
||||
|
||||
<div ref="scrollRoot" class="library-main">
|
||||
<div v-if="loading && !items.length" class="artifact-rows">
|
||||
<div v-for="n in 6" :key="'skel-' + n" class="artifact-row is-skeleton">
|
||||
<t-skeleton animation="gradient" :row-col="[[{ width: '32px', height: '38px', type: 'rect' },
|
||||
{ width: '40%', height: '14px' }]]" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<EmptyState
|
||||
v-else-if="loadError && !items.length"
|
||||
icon="error-circle"
|
||||
:title="$t('artifactLibrary.loadFailed')"
|
||||
>
|
||||
<t-button variant="outline" @click="reload">{{ $t('artifactLibrary.retry') }}</t-button>
|
||||
</EmptyState>
|
||||
|
||||
<EmptyState
|
||||
v-else-if="!items.length && isFiltered"
|
||||
icon="search"
|
||||
:title="$t('artifactLibrary.noMatches.title')"
|
||||
:description="$t('artifactLibrary.noMatches.description')"
|
||||
>
|
||||
<t-button variant="outline" @click="clearFilters">{{ $t('artifactLibrary.clearFilters') }}</t-button>
|
||||
</EmptyState>
|
||||
|
||||
<EmptyState
|
||||
v-else-if="!items.length"
|
||||
icon="folder-open"
|
||||
:title="$t('artifactLibrary.empty.title')"
|
||||
:description="$t('artifactLibrary.empty.description')"
|
||||
/>
|
||||
|
||||
<template v-else>
|
||||
<div class="result-count">{{ $t('artifactLibrary.total', { count: total }) }}</div>
|
||||
<section v-for="section in sections" :key="section.group" class="date-section">
|
||||
<h3 class="date-heading">{{ $t(`artifactLibrary.groups.${section.group}`) }}</h3>
|
||||
<ul class="artifact-rows">
|
||||
<li
|
||||
v-for="item in section.items"
|
||||
:key="`${item.message_id}:${item.index}`"
|
||||
class="artifact-row"
|
||||
@click="openPreview(item)"
|
||||
>
|
||||
<button type="button" class="artifact-open" :title="$t('artifactLibrary.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="meta-sep">·</span>
|
||||
<span>{{ formatArtifactDateTime(item.created_at) }}</span>
|
||||
<template v-if="item.version_count > 1">
|
||||
<span class="meta-sep">·</span>
|
||||
<span class="version-badge">
|
||||
{{ $t('artifactLibrary.versions', { count: item.version_count }) }}
|
||||
</span>
|
||||
</template>
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="session-link"
|
||||
:title="$t('artifactLibrary.openSession')"
|
||||
@click.stop="openSession(item)"
|
||||
>
|
||||
<t-icon name="chat" size="14px" />
|
||||
<span>{{ item.session_title || $t('artifactLibrary.untitledSession') }}</span>
|
||||
</button>
|
||||
<t-button
|
||||
class="row-action"
|
||||
variant="text"
|
||||
shape="square"
|
||||
size="small"
|
||||
:title="$t('artifactLibrary.download')"
|
||||
:aria-label="$t('artifactLibrary.download')"
|
||||
:loading="isDownloading(item)"
|
||||
@click.stop="handleDownload(item)"
|
||||
>
|
||||
<template #icon><t-icon name="download" size="16px" /></template>
|
||||
</t-button>
|
||||
<t-button
|
||||
class="row-action row-action--danger"
|
||||
variant="text"
|
||||
shape="square"
|
||||
size="small"
|
||||
:title="$t('artifactLibrary.delete')"
|
||||
:aria-label="$t('artifactLibrary.delete')"
|
||||
:loading="isDeleting(item)"
|
||||
@click.stop="handleDelete(item)"
|
||||
>
|
||||
<template #icon><t-icon name="delete" size="16px" /></template>
|
||||
</t-button>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<div ref="sentinel" class="list-footer">
|
||||
<t-loading v-if="loading" size="small" />
|
||||
<t-button v-else-if="hasMore" variant="text" @click="loadMore">
|
||||
{{ $t('artifactLibrary.loadMore') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<t-drawer
|
||||
v-model:visible="previewVisible"
|
||||
class="artifact-library-preview"
|
||||
placement="right"
|
||||
size="min(880px, 92vw)"
|
||||
attach="body"
|
||||
:footer="false"
|
||||
:close-on-overlay-click="true"
|
||||
:close-on-esc-keydown="true"
|
||||
@closed="previewItem = null"
|
||||
>
|
||||
<template #header>
|
||||
<div v-if="previewItem" class="preview-header">
|
||||
<ArtifactFileIcon class="preview-header-icon" :file-name="previewItem.file_name" />
|
||||
<div class="preview-header-text">
|
||||
<div class="preview-header-title" :title="previewItem.file_name">{{ previewItem.file_name }}</div>
|
||||
<button type="button" class="session-link session-link--inline" @click="openSession(previewItem)">
|
||||
<t-icon name="chat" size="12px" />
|
||||
<span>{{ previewItem.session_title || $t('artifactLibrary.untitledSession') }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div ref="previewActions" class="preview-actions" />
|
||||
<t-button
|
||||
class="row-action"
|
||||
variant="text"
|
||||
shape="square"
|
||||
size="small"
|
||||
:title="$t('artifactLibrary.download')"
|
||||
:aria-label="$t('artifactLibrary.download')"
|
||||
:loading="isDownloading(previewItem)"
|
||||
@click="handleDownload(previewItem)"
|
||||
>
|
||||
<template #icon><t-icon name="download" size="16px" /></template>
|
||||
</t-button>
|
||||
<t-button
|
||||
class="row-action row-action--danger"
|
||||
variant="text"
|
||||
shape="square"
|
||||
size="small"
|
||||
:title="$t('artifactLibrary.delete')"
|
||||
:aria-label="$t('artifactLibrary.delete')"
|
||||
:loading="isDeleting(previewItem)"
|
||||
@click="handleDelete(previewItem)"
|
||||
>
|
||||
<template #icon><t-icon name="delete" size="16px" /></template>
|
||||
</t-button>
|
||||
<t-button
|
||||
class="row-action"
|
||||
variant="text"
|
||||
shape="square"
|
||||
size="small"
|
||||
:title="$t('common.close')"
|
||||
:aria-label="$t('common.close')"
|
||||
@click="previewVisible = false"
|
||||
>
|
||||
<template #icon><t-icon name="close" size="16px" /></template>
|
||||
</t-button>
|
||||
</div>
|
||||
</template>
|
||||
<div v-if="previewItem" class="preview-body">
|
||||
<DocumentPreview
|
||||
:key="`${previewItem.message_id}:${previewItem.index}`"
|
||||
:toolbar-target="previewActions"
|
||||
:session-id="previewItem.session_id"
|
||||
:message-id="previewItem.message_id"
|
||||
:artifact-index="previewItem.index"
|
||||
:file-type="previewFileType"
|
||||
:file-name="previewItem.file_name"
|
||||
:active="previewVisible"
|
||||
fill-height
|
||||
/>
|
||||
</div>
|
||||
</t-drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { downloadArtifact } from '@/api/chat'
|
||||
import { deleteArtifactLibraryItem, listArtifactLibrary, type ArtifactLibraryItem } from '@/api/artifacts'
|
||||
import {
|
||||
ARTIFACT_CATEGORIES,
|
||||
artifactCategoryExtensions,
|
||||
groupArtifactsByDate,
|
||||
parseArtifactCategory,
|
||||
type ArtifactCategory,
|
||||
} from '@/utils/artifactLibrary'
|
||||
import { formatArtifactDateTime, formatArtifactSize } from '@/utils/sessionArtifacts'
|
||||
import { resolveFilePreviewExt } from '@/utils/filePreview'
|
||||
import { useConfirmDelete } from '@/components/settings/useConfirmDelete'
|
||||
import EmptyState from '@/components/EmptyState.vue'
|
||||
import ResourceIcon from '@/components/icons/ResourceIcon.vue'
|
||||
import DocumentPreview from '@/components/document-preview.vue'
|
||||
import ArtifactFileIcon from '@/views/chat/components/ArtifactFileIcon.vue'
|
||||
|
||||
const PAGE_SIZE = 30
|
||||
const SEARCH_DEBOUNCE_MS = 300
|
||||
|
||||
const { t } = useI18n()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const confirmDelete = useConfirmDelete()
|
||||
|
||||
const category = ref<ArtifactCategory>(parseArtifactCategory(route.query.type))
|
||||
const keyword = ref(typeof route.query.q === 'string' ? route.query.q : '')
|
||||
const items = ref<ArtifactLibraryItem[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(0)
|
||||
const loading = ref(false)
|
||||
const loadError = ref(false)
|
||||
const downloading = reactive<Record<string, boolean>>({})
|
||||
const deleting = reactive<Record<string, boolean>>({})
|
||||
const previewItem = ref<ArtifactLibraryItem | null>(null)
|
||||
const previewVisible = ref(false)
|
||||
const previewActions = ref<HTMLElement | null>(null)
|
||||
const scrollRoot = ref<HTMLElement | null>(null)
|
||||
const sentinel = ref<HTMLElement | null>(null)
|
||||
|
||||
const sections = computed(() => groupArtifactsByDate(items.value))
|
||||
const hasMore = computed(() => items.value.length < total.value)
|
||||
const isFiltered = computed(() => category.value !== 'all' || keyword.value.trim() !== '')
|
||||
const previewFileType = computed(() => {
|
||||
const item = previewItem.value
|
||||
return item ? resolveFilePreviewExt(item.file_name, item.file_type) : ''
|
||||
})
|
||||
|
||||
// Every fetch takes a ticket; a response whose ticket is stale (the filters
|
||||
// changed while it was in flight) is dropped.
|
||||
let ticket = 0
|
||||
|
||||
async function fetchPage(nextPage: number) {
|
||||
const mine = ++ticket
|
||||
loading.value = true
|
||||
loadError.value = false
|
||||
try {
|
||||
const res = await listArtifactLibrary({
|
||||
keyword: keyword.value,
|
||||
fileTypes: artifactCategoryExtensions(category.value),
|
||||
page: nextPage,
|
||||
pageSize: PAGE_SIZE,
|
||||
})
|
||||
if (mine !== ticket) return
|
||||
const rows = Array.isArray(res?.data) ? res.data : []
|
||||
// Deleting a row shifts every later row one page-offset earlier, so an
|
||||
// appended page can overlap what is already shown. Drop the repeats rather
|
||||
// than rendering an item twice under the same key.
|
||||
if (nextPage === 1) {
|
||||
items.value = rows
|
||||
} else {
|
||||
const shown = new Set(items.value.map(itemKey))
|
||||
items.value = [...items.value, ...rows.filter((row) => !shown.has(itemKey(row)))]
|
||||
}
|
||||
total.value = typeof res?.total === 'number' ? res.total : items.value.length
|
||||
page.value = nextPage
|
||||
} catch (err) {
|
||||
if (mine !== ticket) return
|
||||
console.error('[ArtifactLibrary] load failed:', err)
|
||||
loadError.value = true
|
||||
if (nextPage > 1) MessagePlugin.error(t('artifactLibrary.loadFailed'))
|
||||
} finally {
|
||||
if (mine === ticket) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function reload() {
|
||||
items.value = []
|
||||
total.value = 0
|
||||
page.value = 0
|
||||
void fetchPage(1)
|
||||
}
|
||||
|
||||
function loadMore() {
|
||||
if (loading.value || !hasMore.value) return
|
||||
// Page from how many rows are actually shown, not from the last page number:
|
||||
// after a delete those differ, and paging by number would skip a row.
|
||||
void fetchPage(Math.floor(items.value.length / PAGE_SIZE) + 1)
|
||||
}
|
||||
|
||||
function syncQuery() {
|
||||
const query = { ...route.query }
|
||||
if (category.value === 'all') delete query.type
|
||||
else query.type = category.value
|
||||
const q = keyword.value.trim()
|
||||
if (q) query.q = q
|
||||
else delete query.q
|
||||
void router.replace({ query })
|
||||
}
|
||||
|
||||
function setCategory(next: ArtifactCategory) {
|
||||
if (category.value === next) return
|
||||
category.value = next
|
||||
}
|
||||
|
||||
function clearFilters() {
|
||||
category.value = 'all'
|
||||
keyword.value = ''
|
||||
}
|
||||
|
||||
let searchTimer: ReturnType<typeof setTimeout> | null = null
|
||||
watch(keyword, () => {
|
||||
if (searchTimer) clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(() => {
|
||||
searchTimer = null
|
||||
syncQuery()
|
||||
reload()
|
||||
}, SEARCH_DEBOUNCE_MS)
|
||||
})
|
||||
watch(category, () => {
|
||||
syncQuery()
|
||||
reload()
|
||||
})
|
||||
|
||||
function openPreview(item: ArtifactLibraryItem) {
|
||||
previewItem.value = item
|
||||
previewVisible.value = true
|
||||
}
|
||||
|
||||
function openSession(item: ArtifactLibraryItem) {
|
||||
previewVisible.value = false
|
||||
void router.push(`/platform/chat/${item.session_id}`)
|
||||
}
|
||||
|
||||
function itemKey(item: ArtifactLibraryItem) {
|
||||
return `${item.message_id}:${item.index}`
|
||||
}
|
||||
|
||||
function isDownloading(item: ArtifactLibraryItem) {
|
||||
return !!downloading[itemKey(item)]
|
||||
}
|
||||
|
||||
async function handleDownload(item: ArtifactLibraryItem) {
|
||||
const key = itemKey(item)
|
||||
if (downloading[key]) return
|
||||
downloading[key] = true
|
||||
try {
|
||||
const blob = await downloadArtifact(item.session_id, item.message_id, 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('[ArtifactLibrary] download failed:', err)
|
||||
MessagePlugin.error(t('artifactLibrary.downloadFailed'))
|
||||
} finally {
|
||||
downloading[key] = false
|
||||
}
|
||||
}
|
||||
|
||||
function isDeleting(item: ArtifactLibraryItem) {
|
||||
return !!deleting[itemKey(item)]
|
||||
}
|
||||
|
||||
// A library row is the file, not one regeneration of it, so the confirmation
|
||||
// says how many versions go with it. The bytes are reclaimed server side, which
|
||||
// is why this asks at all.
|
||||
function handleDelete(item: ArtifactLibraryItem) {
|
||||
if (isDeleting(item)) return
|
||||
confirmDelete({
|
||||
title: t('artifactLibrary.deleteTitle'),
|
||||
body:
|
||||
item.version_count > 1
|
||||
? t('artifactLibrary.deleteConfirmVersions', { name: item.file_name, count: item.version_count })
|
||||
: t('artifactLibrary.deleteConfirm', { name: item.file_name }),
|
||||
onConfirm: () => performDelete(item),
|
||||
})
|
||||
}
|
||||
|
||||
async function performDelete(item: ArtifactLibraryItem) {
|
||||
const key = itemKey(item)
|
||||
if (deleting[key]) return
|
||||
deleting[key] = true
|
||||
try {
|
||||
await deleteArtifactLibraryItem(item)
|
||||
// Splice the row out instead of reloading: this is an infinite list, and a
|
||||
// reload would throw away everything the user has scrolled past.
|
||||
const at = items.value.findIndex((row) => itemKey(row) === key)
|
||||
if (at >= 0) {
|
||||
items.value.splice(at, 1)
|
||||
total.value = Math.max(0, total.value - 1)
|
||||
}
|
||||
if (previewItem.value && itemKey(previewItem.value) === key) previewVisible.value = false
|
||||
MessagePlugin.success(t('artifactLibrary.deleted'))
|
||||
} catch (err) {
|
||||
console.error('[ArtifactLibrary] delete failed:', err)
|
||||
MessagePlugin.error(t('artifactLibrary.deleteFailed'))
|
||||
} finally {
|
||||
deleting[key] = false
|
||||
}
|
||||
}
|
||||
|
||||
// Load the next page as the footer scrolls into view; the footer button
|
||||
// covers browsers without IntersectionObserver and failed auto-loads.
|
||||
let observer: IntersectionObserver | null = null
|
||||
watch(sentinel, (el, prev) => {
|
||||
if (prev) observer?.unobserve(prev)
|
||||
if (el) observer?.observe(el)
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
if (typeof IntersectionObserver !== 'undefined') {
|
||||
observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (entries.some((e) => e.isIntersecting) && !loadError.value) loadMore()
|
||||
},
|
||||
{ root: scrollRoot.value, rootMargin: '200px' },
|
||||
)
|
||||
if (sentinel.value) observer.observe(sentinel.value)
|
||||
}
|
||||
void fetchPage(1)
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
observer?.disconnect()
|
||||
if (searchTimer) clearTimeout(searchTimer)
|
||||
ticket++
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
@import '@/components/css/artifact-filter-tabs.less';
|
||||
@import (reference) '@/components/css/resource-card.less';
|
||||
|
||||
.artifact-library { .resource-list-content(); }
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 16px;
|
||||
flex-shrink: 0;
|
||||
|
||||
.header-title {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
h2 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
color: var(--td-text-color-primary);
|
||||
font-family: var(--app-font-family);
|
||||
font-size: var(--app-text-4xl);
|
||||
font-weight: 600;
|
||||
line-height: 32px;
|
||||
}
|
||||
}
|
||||
|
||||
.header-subtitle {
|
||||
margin: 0;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-base);
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--app-space-3);
|
||||
padding-bottom: var(--app-space-3);
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
}
|
||||
|
||||
// 与右侧 32px 的搜索框同高:3px 内边距 × 2 + 26px 按钮
|
||||
.category-tabs {
|
||||
.artifact-filter-tabs();
|
||||
button { display: inline-flex; align-items: center; height: 26px; padding: 0 12px; }
|
||||
}
|
||||
|
||||
.search-input {
|
||||
width: 260px;
|
||||
max-width: 100%;
|
||||
:deep(.t-input) { border-radius: var(--app-radius-sm); }
|
||||
}
|
||||
|
||||
.library-main {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: var(--app-space-3) 0 var(--app-space-6);
|
||||
}
|
||||
|
||||
.result-count {
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-sm);
|
||||
padding: 0 var(--app-space-2) var(--app-space-1);
|
||||
}
|
||||
|
||||
.date-section + .date-section {
|
||||
margin-top: var(--app-space-3);
|
||||
}
|
||||
|
||||
.date-heading {
|
||||
margin: 0;
|
||||
padding: var(--app-space-2) var(--app-space-2) var(--app-space-1);
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-sm);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.artifact-rows {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.artifact-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--app-space-3);
|
||||
padding: 10px var(--app-space-2);
|
||||
border-radius: var(--app-radius-md);
|
||||
cursor: pointer;
|
||||
transition: background var(--app-motion-fast) ease;
|
||||
|
||||
&:hover {
|
||||
background: var(--td-bg-color-container-hover);
|
||||
}
|
||||
|
||||
&.is-skeleton {
|
||||
cursor: default;
|
||||
|
||||
&:hover {
|
||||
background: transparent;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.artifact-open {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--app-space-3);
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--td-text-color-secondary);
|
||||
outline-offset: 4px;
|
||||
border-radius: var(--app-radius-xs);
|
||||
}
|
||||
}
|
||||
|
||||
.artifact-body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.artifact-name {
|
||||
display: block;
|
||||
color: var(--td-text-color-primary);
|
||||
font-size: var(--app-text-base);
|
||||
font-weight: 500;
|
||||
line-height: 1.4;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.artifact-meta {
|
||||
margin-top: 2px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--app-space-1);
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.3;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.meta-sep {
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.version-badge {
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.session-link {
|
||||
flex: 0 1 240px;
|
||||
min-width: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--app-space-1);
|
||||
padding: 4px 8px;
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: transparent;
|
||||
color: var(--td-text-color-secondary);
|
||||
font: inherit;
|
||||
font-size: var(--app-text-sm);
|
||||
cursor: pointer;
|
||||
transition: background var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
|
||||
|
||||
span {
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.t-icon {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--td-brand-color);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
&--inline {
|
||||
flex: none;
|
||||
max-width: 100%;
|
||||
padding: 0;
|
||||
margin-top: 2px;
|
||||
|
||||
&:hover {
|
||||
background: transparent;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.row-action.t-button {
|
||||
flex-shrink: 0;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: var(--app-radius-sm);
|
||||
color: var(--td-text-color-secondary);
|
||||
|
||||
&: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);
|
||||
}
|
||||
|
||||
:deep(.t-button__icon) {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
&--danger:not(.t-is-disabled):not(.t-is-loading):hover {
|
||||
background: var(--td-error-color-1);
|
||||
color: var(--td-error-color);
|
||||
}
|
||||
}
|
||||
|
||||
.list-footer {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
min-height: 40px;
|
||||
padding-top: var(--app-space-3);
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.artifact-library {
|
||||
margin: 0;
|
||||
padding: var(--app-space-4) var(--app-space-4) 0;
|
||||
}
|
||||
|
||||
.search-input {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.session-link:not(.session-link--inline) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="less">
|
||||
.artifact-library-preview {
|
||||
.t-drawer__header {
|
||||
padding: 10px 16px;
|
||||
}
|
||||
|
||||
.t-drawer__body {
|
||||
padding: 8px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.preview-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--app-space-2);
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.preview-header-icon {
|
||||
width: 26px;
|
||||
height: 32px;
|
||||
}
|
||||
|
||||
.preview-header-text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.preview-header-title {
|
||||
color: var(--td-text-color-primary);
|
||||
font-size: var(--app-text-md);
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.preview-actions {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.preview-body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,19 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
|
||||
const source = readFileSync(new URL('./Login.vue', import.meta.url), 'utf8')
|
||||
const tabletStyles = source.slice(
|
||||
source.indexOf('@media (max-width: 768px)'),
|
||||
source.indexOf('@media (max-width: 480px)'),
|
||||
)
|
||||
const phoneStyles = source.slice(source.indexOf('@media (max-width: 480px)'))
|
||||
|
||||
test('phone login puts the form before the showcase and reserves room for the header', () => {
|
||||
assert.match(tabletStyles, /\.login-layout\s*\{[\s\S]*?flex-direction:\s*column;[\s\S]*?padding-top:\s*64px;/)
|
||||
assert.match(tabletStyles, /\.form-section\s*\{[\s\S]*?order:\s*-1;/)
|
||||
})
|
||||
|
||||
test('narrow login headers use icon-only links to avoid overlapping the logo', () => {
|
||||
assert.match(phoneStyles, /\.header-links\s*\{[\s\S]*?\.link-text\s*\{\s*display:\s*none;/)
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,245 @@
|
||||
<template>
|
||||
<main class="workspace-onboarding">
|
||||
<section class="workspace-card">
|
||||
<div class="workspace-mark" aria-hidden="true">
|
||||
<t-icon name="system-sum" size="30px" />
|
||||
</div>
|
||||
<h1 v-if="authStore.canCreateTenant">{{ $t('auth.workspaceOnboarding.title') }}</h1>
|
||||
<h1 v-else>{{ $t('auth.workspaceOnboarding.inviteOnlyTitle') }}</h1>
|
||||
<p v-if="authStore.canCreateTenant" class="workspace-description">
|
||||
{{ $t('auth.workspaceOnboarding.description') }}
|
||||
</p>
|
||||
<p v-else class="workspace-description">
|
||||
{{ $t('auth.workspaceOnboarding.inviteOnlyDescription') }}
|
||||
</p>
|
||||
|
||||
<div v-if="policyLoading" class="policy-loading">
|
||||
<t-loading size="small" />
|
||||
<span>{{ $t('auth.workspaceOnboarding.loadingPolicy') }}</span>
|
||||
</div>
|
||||
<div v-else-if="policyLoadFailed" class="policy-error" role="alert">
|
||||
<t-icon name="error-circle" size="20px" aria-hidden="true" />
|
||||
<span>{{ $t('auth.workspaceOnboarding.policyLoadFailed') }}</span>
|
||||
<t-button size="small" variant="text" @click="loadPolicy">
|
||||
{{ $t('auth.workspaceOnboarding.retry') }}
|
||||
</t-button>
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<div v-if="!authStore.canCreateTenant" class="invite-only-notice">
|
||||
<t-icon name="lock-on" size="20px" aria-hidden="true" />
|
||||
<span>{{ $t('auth.workspaceOnboarding.inviteOnlyNotice') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="workspace-actions" :class="{ 'workspace-actions--single': !authStore.canCreateTenant }">
|
||||
<t-button v-if="authStore.canCreateTenant" theme="primary" size="large" @click="createVisible = true">
|
||||
<template #icon><t-icon name="add" /></template>
|
||||
{{ $t('auth.workspaceOnboarding.create') }}
|
||||
</t-button>
|
||||
<t-button
|
||||
:theme="authStore.canCreateTenant ? 'default' : 'primary'"
|
||||
:variant="authStore.canCreateTenant ? 'outline' : 'base'"
|
||||
size="large"
|
||||
@click="invitationsVisible = true"
|
||||
>
|
||||
<template #icon><t-icon name="mail" /></template>
|
||||
{{ $t('auth.workspaceOnboarding.invitations') }}
|
||||
<template v-if="authStore.pendingInvitationCount > 0">
|
||||
({{ authStore.pendingInvitationCount }})
|
||||
</template>
|
||||
</t-button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<p v-if="!policyLoading && !policyLoadFailed && authStore.canCreateTenant" class="workspace-help">
|
||||
{{ $t('auth.workspaceOnboarding.help') }}
|
||||
</p>
|
||||
<p v-else-if="!policyLoading && !policyLoadFailed" class="workspace-help">
|
||||
{{ $t('auth.workspaceOnboarding.inviteOnlyHelp') }}
|
||||
</p>
|
||||
<button class="logout-link" type="button" @click="handleLogout">
|
||||
{{ $t('auth.logout') }}
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<CreateTenantDialog v-model:visible="createVisible" @created="onTenantCreated" />
|
||||
<MyInvitationsDialog v-model:visible="invitationsVisible" />
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import CreateTenantDialog from '@/components/CreateTenantDialog.vue'
|
||||
import MyInvitationsDialog from '@/components/MyInvitationsDialog.vue'
|
||||
import { logout as logoutApi } from '@/api/auth'
|
||||
import type { TenantInfo } from '@/api/tenant'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
|
||||
const router = useRouter()
|
||||
const authStore = useAuthStore()
|
||||
const createVisible = ref(false)
|
||||
const invitationsVisible = ref(false)
|
||||
const policyLoading = ref(true)
|
||||
const policyLoadFailed = ref(false)
|
||||
|
||||
async function loadPolicy() {
|
||||
policyLoading.value = true
|
||||
policyLoadFailed.value = false
|
||||
try {
|
||||
const refreshed = await authStore.refreshFromAuthMe()
|
||||
if (!refreshed) {
|
||||
policyLoadFailed.value = true
|
||||
return
|
||||
}
|
||||
await authStore.fetchPendingInvitationCount()
|
||||
} finally {
|
||||
policyLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadPolicy()
|
||||
})
|
||||
|
||||
watch(
|
||||
() => authStore.hasValidTenant,
|
||||
(ready) => {
|
||||
if (ready) router.replace('/platform/knowledge-bases')
|
||||
},
|
||||
)
|
||||
|
||||
async function onTenantCreated(tenant: TenantInfo) {
|
||||
await authStore.refreshFromAuthMe()
|
||||
authStore.setSelectedTenant(tenant.id, tenant.name)
|
||||
await router.replace('/platform/knowledge-bases')
|
||||
}
|
||||
|
||||
async function handleLogout() {
|
||||
await logoutApi()
|
||||
authStore.logout()
|
||||
await router.replace('/login')
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.workspace-onboarding {
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 32px 20px;
|
||||
background:
|
||||
radial-gradient(circle at 20% 10%, color-mix(in srgb, var(--td-brand-color) 12%, transparent), transparent 38%),
|
||||
var(--td-bg-color-page);
|
||||
}
|
||||
|
||||
.workspace-card {
|
||||
width: min(520px, 100%);
|
||||
padding: 44px;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: 20px;
|
||||
background: var(--td-bg-color-container);
|
||||
box-shadow: var(--td-shadow-2);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.workspace-mark {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
margin: 0 auto 22px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
border-radius: 18px;
|
||||
color: var(--td-brand-color);
|
||||
background: var(--td-brand-color-light);
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
color: var(--td-text-color-primary);
|
||||
font-size: 26px;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.workspace-description,
|
||||
.workspace-help {
|
||||
color: var(--td-text-color-secondary);
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.workspace-description {
|
||||
margin: 14px 0 28px;
|
||||
}
|
||||
|
||||
.workspace-actions {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.workspace-actions--single {
|
||||
grid-template-columns: minmax(220px, 1fr);
|
||||
}
|
||||
|
||||
.policy-loading,
|
||||
.invite-only-notice,
|
||||
.policy-error {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
min-height: 52px;
|
||||
margin-bottom: 18px;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-base);
|
||||
}
|
||||
|
||||
.policy-error {
|
||||
flex-wrap: wrap;
|
||||
padding: 12px 16px;
|
||||
border-radius: var(--app-radius-lg);
|
||||
color: var(--td-error-color);
|
||||
background: var(--td-error-color-light);
|
||||
}
|
||||
|
||||
.invite-only-notice {
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-lg);
|
||||
color: var(--td-text-color-primary);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.invite-only-notice :deep(.t-icon) {
|
||||
flex: 0 0 auto;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.workspace-help {
|
||||
margin: 24px 0 8px;
|
||||
font-size: var(--app-text-md);
|
||||
}
|
||||
|
||||
.logout-link {
|
||||
border: 0;
|
||||
padding: 6px 10px;
|
||||
color: var(--td-text-color-secondary);
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.logout-link:hover {
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
@media (max-width: 560px) {
|
||||
.workspace-card {
|
||||
padding: 32px 22px;
|
||||
}
|
||||
|
||||
.workspace-actions {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,16 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { canRegister } from './registrationPolicy'
|
||||
|
||||
for (const [mode, withoutInvite, withInvite] of [
|
||||
['self_serve', true, true],
|
||||
['invite_register', false, true],
|
||||
['invite_only', false, false],
|
||||
['', false, false],
|
||||
['unknown', false, false],
|
||||
] as const) {
|
||||
test(`registration entry for ${mode || 'unavailable configuration'}`, () => {
|
||||
assert.equal(canRegister(mode, false), withoutInvite)
|
||||
assert.equal(canRegister(mode, true), withInvite)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/** Whether the login page may offer password registration. */
|
||||
export function canRegister(mode: string, hasValidInvitation: boolean): boolean {
|
||||
return mode === 'self_serve' || (mode === 'invite_register' && hasValidInvitation)
|
||||
}
|
||||
@@ -0,0 +1,880 @@
|
||||
<template>
|
||||
<SettingDrawer :visible="visible" :title="automation?.name || ''" icon="time" width="720px" :min-width="480"
|
||||
:max-width="960" storage-key="setting-drawer:width:automation-detail" class="automation-detail-drawer" hide-footer
|
||||
@update:visible="(v: boolean) => !v && close()">
|
||||
<template #headerIcon><t-icon name="time" class="automation-detail__header-icon" /></template>
|
||||
<template v-if="automation" #subtitle>
|
||||
<span class="automation-detail__subtitle">
|
||||
<t-tag v-if="hasEndedOnceSchedule(automation)" size="small" variant="light" :title="t('automation.scheduleEndedHint')">{{ t('automation.scheduleEnded') }}</t-tag>
|
||||
<AutomationStatusTag v-else-if="!automation.enabled" status="paused" />
|
||||
<span>{{ describeTrigger(automation.trigger, t, locale) }} · {{ automation.trigger.timezone || 'UTC' }}</span>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<template v-if="automation" #header-actions>
|
||||
<div class="automation-detail__actions">
|
||||
<t-popconfirm :content="t('automation.runConfirm', { name: automation.name })" theme="default" placement="bottom-right"
|
||||
:confirm-btn="{ content: t('automation.actions.runNow'), theme: 'primary' }" :cancel-btn="t('common.cancel')"
|
||||
:popup-props="{ zIndex: 2600, disabled: !!busy }" @confirm="runNow">
|
||||
<button type="button" class="automation-detail__icon-btn" :disabled="!!busy" :aria-busy="busy === 'run'"
|
||||
:title="t('automation.actions.runNow')" :aria-label="t('automation.actions.runNow')">
|
||||
<t-loading v-if="busy === 'run'" size="14px" />
|
||||
<ChatActionIcon v-else name="play" />
|
||||
</button>
|
||||
</t-popconfirm>
|
||||
<button v-if="!hasEndedOnceSchedule(automation)" type="button" class="automation-detail__icon-btn" :disabled="!!busy" :aria-busy="busy === 'toggle'"
|
||||
:title="automation.enabled ? t('automation.actions.pause') : t('automation.actions.resume')"
|
||||
:aria-label="automation.enabled ? t('automation.actions.pause') : t('automation.actions.resume')" @click="toggle">
|
||||
<t-loading v-if="busy === 'toggle'" size="14px" />
|
||||
<ChatActionIcon v-else :name="automation.enabled ? 'pause' : 'resume'" />
|
||||
</button>
|
||||
<button type="button" class="automation-detail__icon-btn" :title="t('common.edit')"
|
||||
:aria-label="t('common.edit')" @click="emit('edit', automation)">
|
||||
<ChatActionIcon name="edit" />
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-if="automation">
|
||||
<t-alert v-if="!automation.enabled && automation.paused_reason" theme="warning" class="automation-detail__alert"
|
||||
:message="t('automation.detail.pausedBecause', { reason: automation.paused_reason })" />
|
||||
<section class="automation-detail__brief" :aria-label="t('automation.detail.task')">
|
||||
<div class="automation-detail__brief-heading">
|
||||
<div class="automation-detail__brief-context">
|
||||
<h3>{{ t('automation.detail.task') }}</h3>
|
||||
<div class="automation-detail__execution">
|
||||
<span :title="t('automation.fields.accessLevel')">{{ t(`assistant.access.levels.${automation.access_level}.label`) }}</span>
|
||||
<span :title="t('automation.fields.sessionMode')">{{ t(`automation.sessionMode.${automation.session_mode}`) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<t-popup v-model:visible="grantsVisible" trigger="click" placement="bottom-right" :z-index="2600">
|
||||
<button type="button" class="automation-detail__grants-trigger" :class="{ 'is-attention': candidates.length }"
|
||||
:aria-expanded="grantsVisible">
|
||||
<t-icon name="secured" size="14px" />
|
||||
{{ t('automation.detail.grants') }}
|
||||
<span v-if="candidates.length || grants.length" class="automation-detail__count"
|
||||
:title="candidates.length ? t('automation.grants.candidates') : t('automation.grants.active')">
|
||||
{{ candidates.length || grants.length }}
|
||||
</span>
|
||||
<t-icon name="chevron-down" size="12px" />
|
||||
</button>
|
||||
<template #content>
|
||||
<div class="automation-detail__grants-panel" role="region" :aria-label="t('automation.detail.grants')">
|
||||
<h3>{{ t('automation.detail.grants') }}</h3>
|
||||
<p class="automation-detail__muted">{{ t('automation.grants.intro') }}</p>
|
||||
<div v-if="grantsLoading" class="automation-detail__loading"><t-loading size="small" /></div>
|
||||
<template v-else>
|
||||
<ul v-if="grants.length" class="automation-detail__list">
|
||||
<li v-for="grant in grants" :key="grant.id" class="automation-grant">
|
||||
<span class="automation-grant__label">{{ grant.label || grant.grant_key }}</span>
|
||||
<t-tag size="small" variant="light" :theme="grant.risk === 'destructive' ? 'danger' : 'warning'">
|
||||
{{ t(`automation.risk.${grant.risk}`, grant.risk) }}
|
||||
</t-tag>
|
||||
<span v-if="grant.lapse" class="automation-grant__lapse">{{ t('automation.grants.lapsed') }}</span>
|
||||
<t-link theme="danger" hover="color" class="automation-grant__action" @click="revoke(grant)">
|
||||
{{ t('automation.grants.revoke') }}
|
||||
</t-link>
|
||||
</li>
|
||||
</ul>
|
||||
<template v-if="candidates.length">
|
||||
<div class="automation-detail__subhead">{{ t('automation.grants.candidates') }}</div>
|
||||
<ul class="automation-detail__list">
|
||||
<li v-for="candidate in candidates" :key="candidate.prompt_id" class="automation-grant">
|
||||
<span class="automation-grant__label">{{ candidate.label || candidate.tool }}</span>
|
||||
<t-tag size="small" variant="light" :theme="candidate.risk === 'destructive' ? 'danger' : 'warning'">
|
||||
{{ t(`automation.risk.${candidate.risk}`, candidate.risk) }}
|
||||
</t-tag>
|
||||
<span v-if="candidate.service_name" class="automation-grant__meta">{{ candidate.service_name }}</span>
|
||||
<t-link theme="primary" hover="color" class="automation-grant__action" @click="allow(candidate)">
|
||||
{{ t('automation.grants.allow') }}
|
||||
</t-link>
|
||||
</li>
|
||||
</ul>
|
||||
</template>
|
||||
<p v-if="!grants.length && !candidates.length" class="automation-detail__muted">{{ t('automation.grants.none') }}</p>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
</t-popup>
|
||||
</div>
|
||||
<div
|
||||
ref="instructionScroller"
|
||||
class="automation-detail__instruction-scroll"
|
||||
:class="{
|
||||
'automation-detail__instruction-scroll--more': instructionHasMore,
|
||||
'automation-detail__instruction-scroll--expanded': instructionExpanded,
|
||||
}"
|
||||
:style="{ maxHeight: instructionExpanded ? 'none' : `${INSTRUCTION_PREVIEW_HEIGHT}px` }"
|
||||
@scroll="updateInstructionOverflow"
|
||||
>
|
||||
<p ref="instructionContent" class="automation-detail__instruction">{{ automation.instruction }}</p>
|
||||
</div>
|
||||
<button
|
||||
v-if="instructionCanExpand"
|
||||
type="button"
|
||||
class="automation-detail__instruction-toggle"
|
||||
:aria-label="t(instructionExpanded ? 'common.collapse' : 'common.expand')"
|
||||
:title="t(instructionExpanded ? 'common.collapse' : 'common.expand')"
|
||||
:aria-expanded="instructionExpanded"
|
||||
@click="toggleInstruction"
|
||||
>
|
||||
<t-icon :name="instructionExpanded ? 'chevron-up' : 'chevron-down'" size="16px" />
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<section class="automation-detail__history" :aria-label="t('automation.detail.runs')">
|
||||
<div class="automation-detail__history-header">
|
||||
<h3 class="automation-detail__history-heading">
|
||||
{{ t('automation.detail.runs') }}<span class="automation-detail__count">{{ runsTotal }}</span>
|
||||
</h3>
|
||||
<span v-if="automation.enabled && automation.next_run_at" class="automation-detail__next-run">
|
||||
{{ t('automation.fields.nextRun') }}
|
||||
<time :datetime="automation.next_run_at">{{ when(automation.next_run_at) }}</time>
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="runsLoading && !runs.length" class="automation-detail__loading"><t-loading size="small" /></div>
|
||||
<p v-else-if="!runs.length" class="automation-detail__muted">{{ t('automation.detail.noRuns') }}</p>
|
||||
<div v-else class="automation-detail__timeline">
|
||||
<section v-for="group in runGroups" :key="group.date" class="automation-detail__day">
|
||||
<h5 class="automation-detail__date">{{ group.date }}</h5>
|
||||
<ul class="automation-detail__runs">
|
||||
<li v-for="run in group.runs" :key="run.id" class="automation-run" :class="{ 'is-focused': run.id === focusRunId }">
|
||||
<span class="automation-run__marker"><AutomationStatusTag :status="run.status" icon-only /></span>
|
||||
<div class="automation-run__body">
|
||||
<div class="automation-run__head">
|
||||
<time class="automation-run__time" :datetime="run.scheduled_at">{{ runTime(run.scheduled_at) }}</time>
|
||||
<span class="automation-run__meta">
|
||||
{{ t(`automation.runTrigger.${run.trigger_kind}`) }}<template v-if="duration(run)"> · {{ duration(run) }}</template>
|
||||
</span>
|
||||
<t-link v-if="cancellable(run)" theme="danger" hover="color" class="automation-run__stop"
|
||||
:disabled="run.cancel_requested" @click="cancel(run)">
|
||||
{{ run.cancel_requested ? t('automation.detail.stopping') : t('automation.actions.stop') }}
|
||||
</t-link>
|
||||
</div>
|
||||
<component :is="run.session_id ? 'button' : 'div'" class="automation-run__result"
|
||||
:type="run.session_id ? 'button' : undefined"
|
||||
:aria-label="run.session_id ? `${when(run.scheduled_at)} · ${t('automation.actions.openConversation')}` : undefined"
|
||||
@click="run.session_id && openRun(run)">
|
||||
<p v-if="run.error" class="automation-run__text is-error">{{ run.error }}</p>
|
||||
<p v-else-if="run.answer" class="automation-run__text">{{ run.answer }}</p>
|
||||
<span v-else class="automation-detail__muted">{{ t(`automation.status.${run.status}`) }}</span>
|
||||
<t-icon v-if="run.session_id" name="arrow-right-up" size="16px" class="automation-run__chevron" />
|
||||
</component>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
<div v-if="runs.length < runsTotal" class="automation-detail__more">
|
||||
<t-button size="small" variant="text" :loading="runsLoading" @click="loadRuns(false)">
|
||||
{{ t('common.loadMore') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
</SettingDrawer>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'
|
||||
import {
|
||||
addAutomationGrant,
|
||||
cancelAutomationRun,
|
||||
listAutomationGrantCandidates,
|
||||
listAutomationGrants,
|
||||
listAutomationRuns,
|
||||
pauseAutomation,
|
||||
resumeAutomation,
|
||||
revokeAutomationGrant,
|
||||
runAutomationNow,
|
||||
type Automation,
|
||||
type AutomationGrant,
|
||||
type AutomationGrantCandidate,
|
||||
type AutomationRun,
|
||||
} from '@/api/automation'
|
||||
import { describeTrigger, formatInZone, hasEndedOnceSchedule } from '@/utils/automationSchedule'
|
||||
import { useAssistantDataChange } from '@/utils/assistantDataChange'
|
||||
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
|
||||
import AutomationStatusTag from './AutomationStatusTag.vue'
|
||||
import ChatActionIcon from '@/components/ChatActionIcon.vue'
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean
|
||||
automation: Automation | null
|
||||
focusRunId?: string
|
||||
}>()
|
||||
const emit = defineEmits<{
|
||||
'update:visible': [value: boolean]
|
||||
changed: [value: Automation]
|
||||
edit: [value: Automation]
|
||||
}>()
|
||||
|
||||
const { t, locale } = useI18n()
|
||||
const router = useRouter()
|
||||
|
||||
const PAGE = 20
|
||||
const busy = ref<'' | 'run' | 'toggle'>('')
|
||||
const grantsVisible = ref(false)
|
||||
const runs = ref<AutomationRun[]>([])
|
||||
const runsTotal = ref(0)
|
||||
const runsPage = ref(0)
|
||||
const runsLoading = ref(false)
|
||||
const grants = ref<AutomationGrant[]>([])
|
||||
const candidates = ref<AutomationGrantCandidate[]>([])
|
||||
const grantsLoading = ref(false)
|
||||
const instructionScroller = ref<HTMLElement | null>(null)
|
||||
const instructionContent = ref<HTMLElement | null>(null)
|
||||
const instructionHasMore = ref(false)
|
||||
const instructionCanExpand = ref(false)
|
||||
const instructionExpanded = ref(false)
|
||||
const INSTRUCTION_PREVIEW_HEIGHT = 160
|
||||
let poll: ReturnType<typeof setInterval> | undefined
|
||||
let detailVersion = 0
|
||||
let refreshRunsAfterLoad = false
|
||||
|
||||
function updateInstructionOverflow() {
|
||||
const el = instructionScroller.value
|
||||
instructionCanExpand.value = !!el && el.scrollHeight > INSTRUCTION_PREVIEW_HEIGHT + 1
|
||||
instructionHasMore.value = !instructionExpanded.value && !!el && el.scrollHeight - el.clientHeight - el.scrollTop > 1
|
||||
}
|
||||
|
||||
function toggleInstruction() {
|
||||
instructionExpanded.value = !instructionExpanded.value
|
||||
if (instructionScroller.value) instructionScroller.value.scrollTop = 0
|
||||
}
|
||||
|
||||
watch(instructionExpanded, updateInstructionOverflow, { flush: 'post' })
|
||||
|
||||
watch(
|
||||
[instructionScroller, instructionContent, () => props.visible, () => props.automation?.instruction],
|
||||
(_, __, onCleanup) => {
|
||||
updateInstructionOverflow()
|
||||
if (!props.visible || !instructionScroller.value || !instructionContent.value) return
|
||||
const observer = new ResizeObserver(updateInstructionOverflow)
|
||||
observer.observe(instructionScroller.value)
|
||||
observer.observe(instructionContent.value)
|
||||
onCleanup(() => observer.disconnect())
|
||||
},
|
||||
{ flush: 'post' },
|
||||
)
|
||||
|
||||
const when = (iso: string | null) => formatInZone(iso, props.automation?.trigger.timezone, locale.value)
|
||||
const runDateFormatter = computed(() => new Intl.DateTimeFormat(locale.value, {
|
||||
timeZone: props.automation?.trigger.timezone || 'UTC', year: 'numeric', month: 'long', day: 'numeric',
|
||||
}))
|
||||
const runTimeFormatter = computed(() => new Intl.DateTimeFormat(locale.value, {
|
||||
timeZone: props.automation?.trigger.timezone || 'UTC', hour: '2-digit', minute: '2-digit', hour12: false,
|
||||
}))
|
||||
const runTime = (iso: string) => runTimeFormatter.value.format(new Date(iso))
|
||||
const runGroups = computed(() => {
|
||||
const groups = new Map<string, AutomationRun[]>()
|
||||
for (const run of runs.value) {
|
||||
const date = runDateFormatter.value.format(new Date(run.scheduled_at))
|
||||
const group = groups.get(date) ?? []
|
||||
group.push(run)
|
||||
groups.set(date, group)
|
||||
}
|
||||
return [...groups].map(([date, runs]) => ({ date, runs }))
|
||||
})
|
||||
const cancellable = (run: AutomationRun) =>
|
||||
run.status === 'queued' || run.status === 'running' || run.status === 'awaiting_approval'
|
||||
|
||||
function duration(run: AutomationRun): string {
|
||||
if (!run.started_at || !run.finished_at) return ''
|
||||
const seconds = Math.round((Date.parse(run.finished_at) - Date.parse(run.started_at)) / 1000)
|
||||
if (!Number.isFinite(seconds) || seconds < 0) return ''
|
||||
if (seconds < 60) return t('automation.detail.durationSeconds', { n: Math.max(1, seconds) })
|
||||
return t('automation.detail.durationMinutes', { n: Math.round(seconds / 60) })
|
||||
}
|
||||
|
||||
function close() {
|
||||
emit('update:visible', false)
|
||||
}
|
||||
|
||||
async function loadRuns(reset: boolean) {
|
||||
const a = props.automation
|
||||
if (!a) return
|
||||
const version = detailVersion
|
||||
runsLoading.value = true
|
||||
try {
|
||||
const page = reset ? 1 : runsPage.value + 1
|
||||
const res = await listAutomationRuns(a.id, page, PAGE)
|
||||
if (version !== detailVersion) return
|
||||
const items = res.data ?? []
|
||||
runs.value = reset ? items : [...runs.value, ...items]
|
||||
runsTotal.value = res.total ?? runs.value.length
|
||||
runsPage.value = page
|
||||
} catch (e: any) {
|
||||
if (version === detailVersion) MessagePlugin.error(e?.message || t('common.operationFailed'))
|
||||
} finally {
|
||||
if (version === detailVersion) {
|
||||
runsLoading.value = false
|
||||
if (refreshRunsAfterLoad) {
|
||||
refreshRunsAfterLoad = false
|
||||
void refreshActive(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Refresh the first page in place while a run is in flight, so its status
|
||||
// moves without the user reopening the drawer.
|
||||
async function refreshActive(force = false) {
|
||||
const a = props.automation
|
||||
if (!props.visible || !a) return
|
||||
if (runsLoading.value) {
|
||||
if (force) refreshRunsAfterLoad = true
|
||||
return
|
||||
}
|
||||
if (!force && !runs.value.some(cancellable)) return
|
||||
const version = detailVersion
|
||||
try {
|
||||
const res = await listAutomationRuns(a.id, 1, PAGE)
|
||||
if (version !== detailVersion) return
|
||||
const fresh = new Map((res.data ?? []).map((run) => [run.id, run]))
|
||||
const known = new Set(runs.value.map((run) => run.id))
|
||||
runs.value = [
|
||||
...(res.data ?? []).filter((run) => !known.has(run.id)),
|
||||
...runs.value.map((run) => fresh.get(run.id) ?? run),
|
||||
]
|
||||
runsTotal.value = res.total ?? runsTotal.value
|
||||
} catch {
|
||||
// The next tick tries again.
|
||||
}
|
||||
}
|
||||
|
||||
useAssistantDataChange(changes => {
|
||||
if (changes.some(change => change.operation === 'automation.run_now')) void refreshActive(true)
|
||||
}, { areas: ['automation'] })
|
||||
|
||||
async function loadGrants() {
|
||||
const a = props.automation
|
||||
if (!a) return
|
||||
grantsLoading.value = true
|
||||
try {
|
||||
const [g, c] = await Promise.all([listAutomationGrants(a.id), listAutomationGrantCandidates(a.id)])
|
||||
grants.value = g.data ?? []
|
||||
candidates.value = c.data ?? []
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || t('common.operationFailed'))
|
||||
} finally {
|
||||
grantsLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch([() => props.visible, () => props.automation?.id], ([open, id]) => {
|
||||
++detailVersion
|
||||
refreshRunsAfterLoad = false
|
||||
instructionExpanded.value = false
|
||||
clearInterval(poll)
|
||||
if (!open || !id) return
|
||||
grantsVisible.value = false
|
||||
runs.value = []
|
||||
runsTotal.value = 0
|
||||
grants.value = []
|
||||
candidates.value = []
|
||||
void loadRuns(true)
|
||||
void loadGrants()
|
||||
poll = setInterval(refreshActive, 5000)
|
||||
}, { immediate: true })
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
++detailVersion
|
||||
clearInterval(poll)
|
||||
})
|
||||
|
||||
async function runNow() {
|
||||
if (busy.value) return
|
||||
const a = props.automation
|
||||
if (!a) return
|
||||
busy.value = 'run'
|
||||
try {
|
||||
const res = await runAutomationNow(a.id)
|
||||
MessagePlugin.success(t('automation.messages.queued'))
|
||||
if (res.data) {
|
||||
grantsVisible.value = false
|
||||
runs.value = [res.data, ...runs.value]
|
||||
runsTotal.value += 1
|
||||
}
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || t('common.operationFailed'))
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function toggle() {
|
||||
const a = props.automation
|
||||
if (!a || busy.value) return
|
||||
if (hasEndedOnceSchedule(a)) {
|
||||
MessagePlugin.warning(t('automation.scheduleEndedHint'))
|
||||
return
|
||||
}
|
||||
busy.value = 'toggle'
|
||||
try {
|
||||
const res = a.enabled ? await pauseAutomation(a.id) : await resumeAutomation(a.id)
|
||||
emit('changed', res.data)
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || t('common.operationFailed'))
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
function openRun(run: AutomationRun) {
|
||||
close()
|
||||
void router.push(`/platform/chat/${encodeURIComponent(run.session_id)}`)
|
||||
}
|
||||
|
||||
async function cancel(run: AutomationRun) {
|
||||
try {
|
||||
const res = await cancelAutomationRun(run.id)
|
||||
runs.value = runs.value.map((r) => (r.id === run.id ? res.data : r))
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || t('common.operationFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
function allow(candidate: AutomationGrantCandidate) {
|
||||
const a = props.automation
|
||||
if (!a) return
|
||||
grantsVisible.value = false
|
||||
const destructive = candidate.risk === 'destructive'
|
||||
const dialog = DialogPlugin.confirm({
|
||||
header: t('automation.grants.allowTitle'),
|
||||
body: t(destructive ? 'automation.grants.allowDestructiveBody' : 'automation.grants.allowBody', {
|
||||
label: candidate.label || candidate.tool,
|
||||
}),
|
||||
theme: destructive ? 'danger' : 'warning',
|
||||
confirmBtn: { content: t('automation.grants.allow'), theme: destructive ? 'danger' : 'primary' },
|
||||
onConfirm: async () => {
|
||||
dialog.hide()
|
||||
try {
|
||||
await addAutomationGrant(a.id, candidate.prompt_id)
|
||||
await loadGrants()
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || t('common.operationFailed'))
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async function revoke(grant: AutomationGrant) {
|
||||
try {
|
||||
await revokeAutomationGrant(grant.id)
|
||||
await loadGrants()
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || t('common.operationFailed'))
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.automation-detail__actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.automation-detail__icon-btn {
|
||||
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: color-mix(in srgb, var(--td-text-color-primary) 55%, transparent);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
color: var(--td-text-color-secondary);
|
||||
background: color-mix(in srgb, var(--td-text-color-primary) 5%, transparent);
|
||||
}
|
||||
&:active:not(:disabled) {
|
||||
background: color-mix(in srgb, var(--td-text-color-primary) 9%, transparent);
|
||||
}
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--td-brand-color-focus);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
&:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.4;
|
||||
}
|
||||
}
|
||||
|
||||
.automation-detail__subtitle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.automation-detail__alert {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.automation-detail__header-icon {
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
:global(.automation-detail-drawer .setting-drawer__header-icon) {
|
||||
color: var(--td-text-color-secondary);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
}
|
||||
|
||||
.automation-detail__next-run {
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-xs);
|
||||
line-height: 1.6;
|
||||
|
||||
time { font-variant-numeric: tabular-nums; }
|
||||
}
|
||||
|
||||
.automation-detail__brief {
|
||||
padding: 14px 16px 16px;
|
||||
border-radius: var(--app-radius-lg);
|
||||
background: color-mix(in srgb, var(--td-bg-color-secondarycontainer) 40%, var(--td-bg-color-container));
|
||||
}
|
||||
|
||||
.automation-detail__brief-heading {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin-bottom: 14px;
|
||||
|
||||
h3 { margin: 0; font-size: var(--app-text-sm); font-weight: 600; color: var(--td-text-color-primary); }
|
||||
}
|
||||
|
||||
.automation-detail__brief-context { min-width: 0; }
|
||||
|
||||
.automation-detail__grants-trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 4px 6px;
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: transparent;
|
||||
color: var(--td-text-color-secondary);
|
||||
font: inherit;
|
||||
font-size: var(--app-text-xs);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover, &[aria-expanded="true"] { color: var(--td-text-color-primary); background: var(--td-bg-color-container-hover); }
|
||||
&:focus-visible { outline: 1px solid var(--td-brand-color-focus); outline-offset: 2px; }
|
||||
&.is-attention { color: var(--td-warning-color); }
|
||||
}
|
||||
|
||||
.automation-detail__count {
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-xs);
|
||||
font-weight: 400;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.is-attention .automation-detail__count { color: inherit; }
|
||||
|
||||
.automation-detail__grants-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
box-sizing: border-box;
|
||||
width: min(380px, calc(100vw - 48px));
|
||||
max-height: min(480px, 65vh);
|
||||
overflow-y: auto;
|
||||
padding: 12px;
|
||||
|
||||
h3 { margin: 0; font-size: var(--app-text-md); font-weight: 600; color: var(--td-text-color-primary); }
|
||||
}
|
||||
|
||||
.automation-detail__execution {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px 0;
|
||||
margin-top: 4px;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-xs);
|
||||
line-height: 1.5;
|
||||
|
||||
> span + span::before { content: '·'; margin: 0 8px; color: var(--td-text-color-placeholder); }
|
||||
}
|
||||
|
||||
.automation-detail__history { margin-top: 24px; }
|
||||
|
||||
.automation-detail__history-header {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px 16px;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.automation-detail__history-heading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
color: var(--td-text-color-primary);
|
||||
font-size: var(--app-text-md);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.automation-detail__instruction-scroll {
|
||||
box-sizing: border-box;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
scrollbar-width: thin;
|
||||
|
||||
&--expanded {
|
||||
overflow: visible;
|
||||
overscroll-behavior: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.automation-detail__instruction-scroll--more {
|
||||
mask-image: linear-gradient(to bottom, #000 calc(100% - 28px), transparent);
|
||||
}
|
||||
|
||||
.automation-detail__instruction-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 32px;
|
||||
height: 24px;
|
||||
margin: 6px auto -6px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-md);
|
||||
background: transparent;
|
||||
color: var(--td-text-color-secondary);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
color: var(--td-text-color-primary);
|
||||
background: var(--td-bg-color-container);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--td-text-color-secondary);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.automation-detail__instruction {
|
||||
margin: 0;
|
||||
color: var(--td-text-color-primary);
|
||||
font-size: var(--app-text-md);
|
||||
line-height: 1.6;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.automation-detail__muted {
|
||||
margin: 0;
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.automation-detail__loading,
|
||||
.automation-detail__more {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.automation-detail__subhead {
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-sm);
|
||||
}
|
||||
|
||||
.automation-detail__list {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-md);
|
||||
list-style: none;
|
||||
|
||||
> li + li {
|
||||
border-top: 1px solid var(--td-component-stroke);
|
||||
}
|
||||
}
|
||||
|
||||
.automation-detail__day + .automation-detail__day { margin-top: 20px; }
|
||||
|
||||
.automation-detail__date {
|
||||
margin: 0 0 12px;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-sm);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.automation-detail__runs {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.automation-run {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
padding-bottom: 20px;
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 9px;
|
||||
top: 24px;
|
||||
bottom: 0;
|
||||
width: 1px;
|
||||
background: var(--td-component-stroke);
|
||||
}
|
||||
&:last-child { padding-bottom: 0; }
|
||||
&:last-child::before { display: none; }
|
||||
&.is-focused .automation-run__result {
|
||||
background: color-mix(in srgb, var(--td-brand-color) 5%, var(--td-bg-color-container));
|
||||
}
|
||||
}
|
||||
|
||||
.automation-run__marker {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
min-width: 20px;
|
||||
padding-top: 2px;
|
||||
}
|
||||
|
||||
.automation-run__result {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
margin-top: 8px;
|
||||
padding: 12px 14px;
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-lg);
|
||||
background: color-mix(in srgb, var(--td-bg-color-secondarycontainer) 40%, var(--td-bg-color-container));
|
||||
text-align: left;
|
||||
font: inherit;
|
||||
transition: background-color var(--app-motion-fast) ease;
|
||||
}
|
||||
|
||||
button.automation-run__result {
|
||||
cursor: pointer;
|
||||
&:hover { background: var(--td-bg-color-container-hover); }
|
||||
&:focus-visible {
|
||||
outline: 1px solid var(--td-brand-color-focus);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.automation-run__body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.automation-run__head {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.automation-run__time {
|
||||
color: var(--td-text-color-primary);
|
||||
font-size: var(--app-text-md);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.automation-run__meta {
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-sm);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.automation-run__stop {
|
||||
margin-left: auto;
|
||||
font-size: var(--app-text-sm);
|
||||
}
|
||||
|
||||
.automation-run__chevron {
|
||||
flex-shrink: 0;
|
||||
margin-left: auto;
|
||||
margin-top: 3px;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.automation-run__text {
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 3;
|
||||
line-clamp: 3;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
color: var(--td-text-color-primary);
|
||||
font-size: var(--app-text-md);
|
||||
line-height: 1.6;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
|
||||
&.is-error {
|
||||
color: var(--td-error-color);
|
||||
}
|
||||
}
|
||||
|
||||
.automation-grant {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
padding: 10px 14px;
|
||||
}
|
||||
|
||||
.automation-grant__label {
|
||||
min-width: 0;
|
||||
flex-basis: 100%;
|
||||
color: var(--td-text-color-primary);
|
||||
font-size: var(--app-text-sm);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.automation-grant__meta,
|
||||
.automation-grant__lapse {
|
||||
font-size: var(--app-text-sm);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.automation-grant__meta {
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.automation-grant__lapse {
|
||||
color: var(--td-warning-color);
|
||||
}
|
||||
|
||||
.automation-grant__action {
|
||||
flex-shrink: 0;
|
||||
margin-left: auto;
|
||||
font-size: var(--app-text-sm);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,750 @@
|
||||
<template>
|
||||
<SettingsModalShell :visible="visible"
|
||||
:title="automation ? t('automation.editor.editTitle') : t('automation.editor.createTitle')"
|
||||
v-model="section" :nav-groups="navGroups" :z-index="1000" @close="modalShell.requestClose">
|
||||
<div class="content-wrapper">
|
||||
<!-- 基本信息 -->
|
||||
<div v-show="section === 'basic'" class="section">
|
||||
<div class="section-header">
|
||||
<h2>{{ t('automation.editor.sections.basic.title') }}</h2>
|
||||
<p class="section-description">{{ t('automation.editor.sections.basic.desc') }}</p>
|
||||
</div>
|
||||
<div class="settings-group">
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('automation.fields.name') }}<span class="required">*</span></label>
|
||||
<p class="desc">{{ t('automation.editor.nameDesc') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-input v-model="form.name" :maxlength="100" :placeholder="t('automation.editor.namePlaceholder')" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('automation.editor.model') }}</label>
|
||||
<p class="desc">{{ t('automation.editor.modelHelp') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<ModelSelector v-model:selected-model-id="form.model_id" model-type="KnowledgeQA" clearable
|
||||
:placeholder="t('automation.editor.modelDefault')" @add-model="uiStore.openSettings('models', 'llm')" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="setting-row setting-row-vertical">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('automation.fields.instruction') }}<span class="required">*</span></label>
|
||||
<p class="desc">{{ t('automation.editor.unattendedHint') }}</p>
|
||||
</div>
|
||||
<div class="setting-control setting-control-full automation-editor__stack">
|
||||
<t-textarea v-model="form.instruction" :autosize="{ minRows: 6, maxRows: 16 }" :maxlength="20000"
|
||||
:placeholder="t('automation.editor.instructionPlaceholder')" />
|
||||
<p class="automation-editor__hint">
|
||||
{{ t('automation.editor.variablesHint') }}
|
||||
<code v-for="tag in VARIABLE_TAGS" :key="tag">{{ tag }}</code>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 运行时间 -->
|
||||
<div v-show="section === 'schedule'" class="section">
|
||||
<div class="section-header">
|
||||
<h2>{{ t('automation.editor.sections.schedule.title') }}</h2>
|
||||
<p class="section-description">{{ t('automation.editor.sections.schedule.desc') }}</p>
|
||||
</div>
|
||||
<div class="settings-group">
|
||||
<div class="setting-row setting-row-vertical">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('automation.editor.frequency') }}<span class="required">*</span></label>
|
||||
</div>
|
||||
<div class="setting-control setting-control-full">
|
||||
<div class="automation-editor__frequency" role="group" :aria-label="t('automation.editor.frequency')">
|
||||
<label v-for="kind in KINDS" :key="kind" class="automation-editor__frequency-option">
|
||||
<input v-model="schedule.kind" type="radio" name="automation-frequency" :value="kind" />
|
||||
<span>{{ t(`automation.schedule.kinds.${kind}`) }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="schedule.kind === 'weekly'" class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('automation.editor.weekdays') }}</label>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-checkbox-group v-model="schedule.days" class="automation-editor__days">
|
||||
<t-checkbox v-for="day in WEEK" :key="day" :value="day">{{ weekdayName(day, locale) }}</t-checkbox>
|
||||
</t-checkbox-group>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="schedule.kind === 'monthly'" class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('automation.schedule.dayOfMonth') }}</label>
|
||||
<p class="desc">{{ t('automation.editor.dayOfMonthDesc') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-input-number v-model="schedule.day" :min="1" :max="31" theme="column" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="schedule.kind === 'hourly'" class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('automation.schedule.atMinute') }}</label>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-input-number v-model="schedule.minute" :min="0" :max="59" theme="column" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="schedule.kind === 'once'" class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('automation.editor.runAt') }}</label>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-date-picker v-model="schedule.at" enable-time-picker format="YYYY-MM-DD HH:mm"
|
||||
value-type="YYYY-MM-DD HH:mm" :placeholder="t('automation.schedule.pickTime')" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="schedule.kind === 'custom'" class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('automation.editor.cron') }}</label>
|
||||
<p class="desc">{{ t('automation.schedule.customHint') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-input v-model="schedule.expr" class="automation-editor__mono" placeholder="0 9 * * 1-5" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('automation.editor.timeOfDay') }}</label>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-time-picker v-model="clock" format="HH:mm" :clearable="false" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('automation.fields.timezone') }}</label>
|
||||
<p class="desc">{{ t('automation.editor.timezoneDesc') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-select v-model="timezone" filterable>
|
||||
<t-option v-for="zone in zones" :key="zone" :value="zone" :label="zone" />
|
||||
</t-select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-row setting-row-vertical">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('automation.schedule.nextRuns') }}</label>
|
||||
</div>
|
||||
<div class="setting-control setting-control-full">
|
||||
<div class="automation-editor__preview" :class="{ 'is-error': previewError }" aria-live="polite">
|
||||
<template v-if="previewError">
|
||||
<t-icon name="error-circle" size="16px" /> {{ previewError }}
|
||||
</template>
|
||||
<ul v-else-if="previewRuns.length" class="automation-editor__runs">
|
||||
<li v-for="run in previewRuns" :key="run">
|
||||
<t-icon name="time" size="14px" /> {{ formatInZone(run, timezone, locale) }}
|
||||
</li>
|
||||
</ul>
|
||||
<span v-else-if="previewLoading">{{ t('common.loading') }}</span>
|
||||
<span v-else class="automation-editor__muted">{{ t('automation.editor.previewEmpty') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 执行方式 -->
|
||||
<div v-show="section === 'execution'" class="section">
|
||||
<div class="section-header">
|
||||
<h2>{{ t('automation.editor.sections.execution.title') }}</h2>
|
||||
<p class="section-description">{{ t('automation.editor.sections.execution.desc') }}</p>
|
||||
</div>
|
||||
<div class="settings-group">
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('automation.fields.accessLevel') }}</label>
|
||||
<p class="desc">{{ t(`automation.editor.access.${form.access_level}`) }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-select v-model="form.access_level">
|
||||
<t-option v-for="level in ASSISTANT_ACCESS_LEVELS" :key="level" :value="level"
|
||||
:label="t(`assistant.access.levels.${level}.label`)" />
|
||||
</t-select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('automation.fields.sessionMode') }}</label>
|
||||
<p class="desc">{{ t(`automation.editor.sessionModeDesc.${form.session_mode}`) }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-select v-model="form.session_mode">
|
||||
<t-option value="per_run" :label="t('automation.sessionMode.per_run')" />
|
||||
<t-option value="persistent" :label="t('automation.sessionMode.persistent')" />
|
||||
</t-select>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="form.session_mode === 'per_run'" class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('automation.fields.carryLastResult') }}</label>
|
||||
<p class="desc">{{ t('automation.editor.carryDesc') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-switch v-model="form.carry_last_result" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('automation.fields.overlapPolicy') }}</label>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-select v-model="form.overlap_policy">
|
||||
<t-option value="skip" :label="t('automation.overlap.skip')" />
|
||||
<t-option value="queue" :label="t('automation.overlap.queue')" />
|
||||
</t-select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('automation.fields.misfirePolicy') }}</label>
|
||||
<p class="desc">{{ t('automation.editor.misfireDesc') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-select v-model="form.misfire_policy">
|
||||
<t-option value="skip" :label="t('automation.misfire.skip')" />
|
||||
<t-option value="run_once" :label="t('automation.misfire.run_once')" />
|
||||
</t-select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('automation.fields.maxDuration') }}</label>
|
||||
<p class="desc">{{ t('automation.editor.maxDurationDesc') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<div class="automation-editor__number">
|
||||
<t-input-number v-model="maxMinutes" :min="1" :max="240" :step="1" :decimal-places="0"
|
||||
theme="row" :allow-input-over-limit="false" :aria-label="t('automation.fields.maxDuration')" />
|
||||
<span>{{ t('automation.units.minutes') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 审批与通知 -->
|
||||
<div v-show="section === 'notify'" class="section">
|
||||
<div class="section-header">
|
||||
<h2>{{ t('automation.editor.sections.notify.title') }}</h2>
|
||||
<p class="section-description">{{ t('automation.editor.sections.notify.desc') }}</p>
|
||||
</div>
|
||||
<div class="settings-group">
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('automation.fields.approvalTimeout') }}</label>
|
||||
<p class="desc">{{ t('automation.editor.approvalTimeoutHelp') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<div class="automation-editor__number">
|
||||
<t-input-number v-model="approvalHours" :min="1" :max="168" :step="1" :decimal-places="0"
|
||||
theme="row" :allow-input-over-limit="false" :aria-label="t('automation.fields.approvalTimeout')" />
|
||||
<span>{{ t('automation.units.hours') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('automation.fields.notifyOnSuccess') }}</label>
|
||||
<p class="desc">{{ t('automation.editor.notifyHint') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-switch v-model="form.notify_on_success" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template #footer-note>
|
||||
<p v-if="previewRuns.length && !previewError" class="automation-editor__next-run">
|
||||
<t-icon name="time" size="14px" />
|
||||
<span>{{ t('automation.fields.nextRun') }}</span>
|
||||
<time :datetime="previewRuns[0]">{{ formatInZone(previewRuns[0], timezone, locale) }}</time>
|
||||
</p>
|
||||
</template>
|
||||
<template #footer>
|
||||
<t-button theme="default" variant="outline" @click="modalShell.requestClose">{{ t('common.cancel') }}</t-button>
|
||||
<t-button theme="primary" :loading="saving" @click="save">
|
||||
{{ automation ? t('common.save') : t('common.create') }}
|
||||
</t-button>
|
||||
</template>
|
||||
</SettingsModalShell>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import SettingsModalShell from '@/components/SettingsModalShell.vue'
|
||||
import { useModalShell } from '@/composables/useModalShell'
|
||||
import {
|
||||
createAutomation,
|
||||
updateAutomation,
|
||||
validateAutomationTrigger,
|
||||
type Automation,
|
||||
type AutomationInput,
|
||||
} from '@/api/automation'
|
||||
import { ASSISTANT_ACCESS_LEVELS } from '@/api/assistant'
|
||||
import {
|
||||
browserTimezone,
|
||||
defaultScheduleForm,
|
||||
formatInZone,
|
||||
scheduleFormFromTrigger,
|
||||
timezoneOptions,
|
||||
triggerFromScheduleForm,
|
||||
weekdayName,
|
||||
type ScheduleKind,
|
||||
} from '@/utils/automationSchedule'
|
||||
import ModelSelector from '@/components/ModelSelector.vue'
|
||||
import { useUIStore } from '@/stores/ui'
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean
|
||||
automation: Automation | null
|
||||
}>()
|
||||
const emit = defineEmits<{ 'update:visible': [value: boolean]; saved: [value: Automation] }>()
|
||||
|
||||
const { t, locale } = useI18n()
|
||||
const uiStore = useUIStore()
|
||||
|
||||
type Section = 'basic' | 'schedule' | 'execution' | 'notify'
|
||||
|
||||
const VARIABLE_TAGS = ['now', 'last_run_at', 'last_success_at', 'run_id', 'automation_name']
|
||||
.map((name) => `{{${name}}}`)
|
||||
const KINDS: ScheduleKind[] = ['daily', 'weekdays', 'weekly', 'monthly', 'hourly', 'once', 'custom']
|
||||
const WEEK = [1, 2, 3, 4, 5, 6, 0]
|
||||
|
||||
const section = ref<Section>('basic')
|
||||
const navGroups = computed(() => [
|
||||
{
|
||||
key: 'task',
|
||||
label: t('automation.editor.navGroups.task'),
|
||||
items: [
|
||||
{ key: 'basic', label: t('automation.editor.sections.basic.title'), icon: 'edit-1' },
|
||||
{ key: 'schedule', label: t('automation.editor.sections.schedule.title'), icon: 'time' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'run',
|
||||
label: t('automation.editor.navGroups.run'),
|
||||
items: [
|
||||
{ key: 'execution', label: t('automation.editor.sections.execution.title'), icon: 'secured' },
|
||||
{ key: 'notify', label: t('automation.editor.sections.notify.title'), icon: 'notification' },
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
const blank = (): Required<Omit<AutomationInput, 'trigger' | 'limits' | 'description'>> => ({
|
||||
name: '',
|
||||
model_id: '',
|
||||
instruction: '',
|
||||
session_mode: 'per_run',
|
||||
carry_last_result: false,
|
||||
misfire_policy: 'skip',
|
||||
overlap_policy: 'skip',
|
||||
access_level: 'confirm',
|
||||
approval_timeout_minutes: 1440,
|
||||
notify_on_success: false,
|
||||
})
|
||||
|
||||
const form = reactive(blank())
|
||||
const schedule = reactive(defaultScheduleForm())
|
||||
const timezone = ref(browserTimezone())
|
||||
const maxMinutes = ref(30)
|
||||
const saving = ref(false)
|
||||
|
||||
const zones = computed(() => timezoneOptions(timezone.value))
|
||||
|
||||
const approvalHours = computed({
|
||||
get: () => Math.max(1, Math.round(form.approval_timeout_minutes / 60)),
|
||||
set: (v: number | undefined) => {
|
||||
if (v === undefined || !Number.isFinite(v)) return
|
||||
form.approval_timeout_minutes = Math.min(168, Math.max(1, Math.round(v))) * 60
|
||||
},
|
||||
})
|
||||
|
||||
const clock = computed({
|
||||
get: () => `${String(schedule.hour).padStart(2, '0')}:${String(schedule.minute).padStart(2, '0')}`,
|
||||
set: (v: string) => {
|
||||
const [h, m] = String(v || '').split(':').map(Number)
|
||||
if (Number.isFinite(h)) schedule.hour = h
|
||||
if (Number.isFinite(m)) schedule.minute = m
|
||||
},
|
||||
})
|
||||
|
||||
const trigger = computed(() => triggerFromScheduleForm(schedule, timezone.value))
|
||||
|
||||
function close() {
|
||||
emit('update:visible', false)
|
||||
}
|
||||
|
||||
const modalShell = useModalShell({
|
||||
visible: () => props.visible,
|
||||
close,
|
||||
snapshot: () => ({ form, schedule, timezone: timezone.value, maxMinutes: maxMinutes.value }),
|
||||
})
|
||||
|
||||
watch(() => props.visible, (open) => {
|
||||
if (!open) return
|
||||
const a = props.automation
|
||||
section.value = 'basic'
|
||||
Object.assign(form, blank())
|
||||
Object.assign(schedule, defaultScheduleForm())
|
||||
timezone.value = browserTimezone()
|
||||
maxMinutes.value = 30
|
||||
if (a) {
|
||||
Object.assign(form, {
|
||||
name: a.name,
|
||||
model_id: a.model_id || '',
|
||||
instruction: a.instruction,
|
||||
session_mode: a.session_mode,
|
||||
carry_last_result: a.carry_last_result,
|
||||
misfire_policy: a.misfire_policy,
|
||||
overlap_policy: a.overlap_policy,
|
||||
access_level: a.access_level,
|
||||
approval_timeout_minutes: a.approval_timeout_minutes,
|
||||
notify_on_success: a.notify_on_success,
|
||||
})
|
||||
Object.assign(schedule, scheduleFormFromTrigger(a.trigger))
|
||||
timezone.value = a.trigger.timezone || 'UTC'
|
||||
maxMinutes.value = a.limits?.max_duration_minutes || 30
|
||||
}
|
||||
previewRuns.value = []
|
||||
previewError.value = ''
|
||||
modalShell.markClean()
|
||||
}, { immediate: true })
|
||||
|
||||
const previewRuns = ref<string[]>([])
|
||||
const previewError = ref('')
|
||||
const previewLoading = ref(false)
|
||||
let previewSeq = 0
|
||||
let previewTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
watch([trigger, () => props.visible], () => {
|
||||
clearTimeout(previewTimer)
|
||||
const current = trigger.value
|
||||
previewRuns.value = []
|
||||
previewError.value = ''
|
||||
if (!props.visible || !current) return
|
||||
previewLoading.value = true
|
||||
const seq = ++previewSeq
|
||||
previewTimer = setTimeout(async () => {
|
||||
try {
|
||||
const res = await validateAutomationTrigger(current)
|
||||
if (seq === previewSeq) previewRuns.value = res.data?.next_runs ?? []
|
||||
} catch (e: any) {
|
||||
if (seq === previewSeq) previewError.value = e?.message || t('automation.schedule.invalid')
|
||||
} finally {
|
||||
if (seq === previewSeq) previewLoading.value = false
|
||||
}
|
||||
}, 400)
|
||||
}, { deep: true })
|
||||
|
||||
// The first section with a problem, with what to tell the user.
|
||||
function firstProblem(): [Section, string] | null {
|
||||
if (!form.name.trim()) return ['basic', t('automation.editor.errors.name')]
|
||||
if (!form.instruction.trim()) return ['basic', t('automation.editor.errors.instruction')]
|
||||
if (!trigger.value || previewError.value) return ['schedule', previewError.value || t('automation.editor.errors.schedule')]
|
||||
return null
|
||||
}
|
||||
|
||||
async function save() {
|
||||
const problem = firstProblem()
|
||||
if (problem) {
|
||||
section.value = problem[0]
|
||||
MessagePlugin.warning(problem[1])
|
||||
return
|
||||
}
|
||||
saving.value = true
|
||||
const input: AutomationInput = {
|
||||
...form,
|
||||
name: form.name.trim(),
|
||||
trigger: trigger.value!,
|
||||
limits: { max_duration_minutes: maxMinutes.value },
|
||||
}
|
||||
try {
|
||||
const res = props.automation
|
||||
? await updateAutomation(props.automation.id, input)
|
||||
: await createAutomation(input)
|
||||
MessagePlugin.success(props.automation ? t('common.saveSuccess') : t('common.createSuccess'))
|
||||
modalShell.markClean()
|
||||
emit('saved', res.data)
|
||||
close()
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || t('common.saveFailed'))
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.automation-editor__next-run {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px 6px;
|
||||
min-width: 0;
|
||||
margin: 0 auto 0 0;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-xs);
|
||||
line-height: 1.6;
|
||||
|
||||
> .t-icon { flex-shrink: 0; }
|
||||
> span { white-space: nowrap; }
|
||||
time { font-variant-numeric: tabular-nums; }
|
||||
}
|
||||
|
||||
.content-wrapper {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
min-height: 0;
|
||||
padding: 28px 40px 48px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.section {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.section-header {
|
||||
margin-bottom: 20px;
|
||||
|
||||
h2 {
|
||||
margin: 0 0 6px;
|
||||
color: var(--td-text-color-primary);
|
||||
font-size: var(--app-text-3xl);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.section-description {
|
||||
margin: 0;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-base);
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
.settings-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.setting-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 24px;
|
||||
min-width: 0;
|
||||
padding: 16px 0;
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
&.setting-row-vertical {
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
|
||||
.setting-info {
|
||||
flex: none;
|
||||
max-width: 100%;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.setting-info {
|
||||
flex: 0 0 42%;
|
||||
max-width: 42%;
|
||||
min-width: 0;
|
||||
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: 4px;
|
||||
color: var(--td-text-color-primary);
|
||||
font-size: var(--app-text-lg);
|
||||
font-weight: 500;
|
||||
|
||||
.required {
|
||||
margin-left: 2px;
|
||||
color: var(--td-error-color);
|
||||
}
|
||||
}
|
||||
|
||||
.desc {
|
||||
margin: 0;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-md);
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
.setting-control {
|
||||
display: flex;
|
||||
flex: 1 1 58%;
|
||||
justify-content: flex-end;
|
||||
align-items: flex-start;
|
||||
min-width: 0;
|
||||
max-width: 58%;
|
||||
|
||||
> :deep(.t-select__wrap),
|
||||
> :deep(.t-input__wrap),
|
||||
> :deep(.t-date-picker) {
|
||||
width: 100%;
|
||||
max-width: 320px;
|
||||
}
|
||||
|
||||
&.setting-control-full {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
.automation-editor__stack {
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.automation-editor__hint {
|
||||
margin: 0;
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.8;
|
||||
|
||||
code {
|
||||
margin: 0 2px;
|
||||
padding: 1px 6px;
|
||||
border-radius: var(--app-radius-xs);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-xs);
|
||||
}
|
||||
}
|
||||
|
||||
.automation-editor__frequency {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.automation-editor__frequency-option {
|
||||
position: relative;
|
||||
cursor: pointer;
|
||||
|
||||
input {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
opacity: 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
span {
|
||||
display: block;
|
||||
padding: 8px 16px;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-pill);
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-base);
|
||||
transition: background-color var(--app-motion-fast) ease, border-color var(--app-motion-fast) ease;
|
||||
}
|
||||
|
||||
&:hover span { background: var(--td-bg-color-container-hover); }
|
||||
input:checked + span {
|
||||
color: var(--td-brand-color);
|
||||
border-color: color-mix(in srgb, var(--td-brand-color) 40%, var(--td-component-stroke));
|
||||
background: color-mix(in srgb, var(--td-brand-color) 7%, var(--td-bg-color-container));
|
||||
font-weight: 500;
|
||||
}
|
||||
input:focus-visible + span {
|
||||
outline: 2px solid var(--td-brand-color-focus);
|
||||
outline-offset: 3px;
|
||||
}
|
||||
}
|
||||
|
||||
.automation-editor__number {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
color: var(--td-text-color-secondary);
|
||||
white-space: nowrap;
|
||||
|
||||
:deep(.t-input-number) {
|
||||
width: 160px;
|
||||
flex: none;
|
||||
}
|
||||
}
|
||||
|
||||
.automation-editor__days {
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
row-gap: 4px;
|
||||
}
|
||||
|
||||
.automation-editor__mono :deep(input) {
|
||||
font-family: var(--app-font-family-mono);
|
||||
}
|
||||
|
||||
.automation-editor__preview {
|
||||
width: 100%;
|
||||
padding: 12px 16px;
|
||||
border-radius: var(--app-radius-md);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
color: var(--td-text-color-primary);
|
||||
font-size: var(--app-text-base);
|
||||
|
||||
&.is-error {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
background: var(--td-error-color-light);
|
||||
color: var(--td-error-color);
|
||||
}
|
||||
}
|
||||
|
||||
.automation-editor__runs {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
font-variant-numeric: tabular-nums;
|
||||
|
||||
li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
:deep(.t-icon) {
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
}
|
||||
|
||||
.automation-editor__muted {
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,607 @@
|
||||
<template>
|
||||
<main class="automation-page">
|
||||
<header class="automation-page__header" style="--wails-draggable: drag">
|
||||
<div class="automation-page__title-row" style="--wails-draggable: drag">
|
||||
<h2 style="--wails-draggable: drag">
|
||||
<ResourceIcon type="automation" :size="24" />
|
||||
{{ t('automation.title') }}
|
||||
</h2>
|
||||
<div class="automation-page__tools" style="--wails-draggable: no-drag">
|
||||
<t-input v-if="automations.length > 0" v-model="query" class="automation-page__search"
|
||||
:placeholder="t('menu.search')" :aria-label="t('menu.search')" clearable>
|
||||
<template #prefix-icon><t-icon name="search" size="16px" /></template>
|
||||
</t-input>
|
||||
<t-button variant="text" theme="default" size="small" class="automation-page__add" @click="openEditor(null)">
|
||||
<template #icon><t-icon name="add" size="16px" /></template>
|
||||
{{ t('automation.add') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="automation-page__subtitle" style="--wails-draggable: drag">{{ t('automation.description') }}</p>
|
||||
</header>
|
||||
|
||||
<div v-if="loading" class="loading-container">
|
||||
<t-loading :text="t('common.loading')" />
|
||||
</div>
|
||||
|
||||
<section v-else class="automation-page__main">
|
||||
<div v-if="automations.length > 0 && filtered.length === 0" class="empty-state">
|
||||
<t-empty :description="t('common.noResult')" />
|
||||
<t-button variant="outline" @click="query = ''">{{ t('common.clear') }}</t-button>
|
||||
</div>
|
||||
<div v-else class="automation-grid">
|
||||
<article v-for="item in filtered" :key="item.id" class="automation-card" :class="{ 'is-paused': !item.enabled }">
|
||||
<button type="button" class="automation-card__open" :aria-label="item.name" @click="openDetail(item)" />
|
||||
<div class="automation-card__header">
|
||||
<div class="automation-card__badge" aria-hidden="true"><t-icon name="time" size="14px" /></div>
|
||||
<h3 class="automation-card__title" :title="item.name">{{ item.name }}</h3>
|
||||
<div class="automation-card__actions">
|
||||
<t-popconfirm :content="t('automation.runConfirm', { name: item.name })"
|
||||
:confirm-btn="{ content: t('automation.actions.runNow'), theme: 'primary' }"
|
||||
:cancel-btn="t('common.cancel')" theme="default" placement="bottom"
|
||||
:popup-props="{ disabled: busy.has(item.id) }" @confirm="runNow(item)">
|
||||
<button type="button" class="automation-card__icon-btn" :title="t('automation.actions.runNow')"
|
||||
:aria-label="`${item.name} · ${t('automation.actions.runNow')}`" :disabled="busy.has(item.id)">
|
||||
<ChatActionIcon name="play" />
|
||||
</button>
|
||||
</t-popconfirm>
|
||||
<button type="button" class="automation-card__icon-btn" :title="t('common.edit')"
|
||||
:aria-label="`${item.name} · ${t('common.edit')}`" @click="openEditor(item)">
|
||||
<ChatActionIcon name="edit" />
|
||||
</button>
|
||||
<t-popconfirm :content="t('automation.deleteBody', { name: item.name })"
|
||||
:confirm-btn="{ content: t('common.delete'), theme: 'danger' }"
|
||||
:cancel-btn="t('common.cancel')" theme="danger" placement="bottom"
|
||||
:popup-props="{ disabled: busy.has(item.id) }" @confirm="remove(item)">
|
||||
<button type="button" class="automation-card__icon-btn" :title="t('common.delete')"
|
||||
:aria-label="`${item.name} · ${t('common.delete')}`" :disabled="busy.has(item.id)">
|
||||
<ChatActionIcon name="delete" />
|
||||
</button>
|
||||
</t-popconfirm>
|
||||
</div>
|
||||
</div>
|
||||
<p class="automation-card__schedule">{{ describeTrigger(item.trigger, t, locale) }}</p>
|
||||
<p v-if="!item.enabled && item.paused_reason" class="automation-card__paused" :title="item.paused_reason">
|
||||
{{ item.paused_reason }}
|
||||
</p>
|
||||
<div class="automation-card__footer">
|
||||
<div class="automation-card__meta">
|
||||
<span v-if="item.enabled && item.next_run_at">
|
||||
{{ t('automation.nextRunAt', { time: formatInZone(item.next_run_at, item.trigger.timezone, locale) }) }}
|
||||
</span>
|
||||
<AutomationStatusTag :status="item.active_run_status || item.last_run_status" />
|
||||
</div>
|
||||
<span v-if="hasEndedOnceSchedule(item)" class="automation-card__status is-ended" :title="t('automation.scheduleEndedHint')">
|
||||
{{ t('automation.scheduleEnded') }}
|
||||
</span>
|
||||
<button v-else type="button" role="switch" class="automation-card__status" :class="{ 'is-enabled': item.enabled }"
|
||||
:aria-checked="item.enabled" :aria-label="`${item.name} · ${t('automation.fields.enabled')}`"
|
||||
:disabled="busy.has(item.id)" @click="toggle(item)">
|
||||
<t-loading v-if="busy.has(item.id)" size="12px" />
|
||||
<span v-else class="automation-card__dot" aria-hidden="true" />
|
||||
{{ item.enabled ? t('common.on') : t('automation.paused') }}
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
<button type="button" class="automation-card automation-card--add" @click="openEditor(null)">
|
||||
<span class="automation-card--add__icon" aria-hidden="true"><t-icon name="add" /></span>
|
||||
<span class="automation-card--add__label">{{ t('automation.add') }}</span>
|
||||
<span class="automation-card--add__hint">{{ t('automation.addHint') }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<AutomationEditor v-model:visible="editorVisible" :automation="editing" @saved="onSaved" />
|
||||
<AutomationDetail v-model:visible="detailVisible" :automation="detail"
|
||||
:focus-run-id="focusRunId" @changed="onSaved" @edit="openEditor" />
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import {
|
||||
deleteAutomation,
|
||||
getAutomation,
|
||||
listAutomations,
|
||||
pauseAutomation,
|
||||
resumeAutomation,
|
||||
runAutomationNow,
|
||||
type Automation,
|
||||
} from '@/api/automation'
|
||||
import { describeTrigger, formatInZone, hasEndedOnceSchedule } from '@/utils/automationSchedule'
|
||||
import { useAssistantDataChange } from '@/utils/assistantDataChange'
|
||||
import AutomationEditor from './AutomationEditor.vue'
|
||||
import AutomationDetail from './AutomationDetail.vue'
|
||||
import AutomationStatusTag from './AutomationStatusTag.vue'
|
||||
import ChatActionIcon from '@/components/ChatActionIcon.vue'
|
||||
import ResourceIcon from '@/components/icons/ResourceIcon.vue'
|
||||
|
||||
const { t, locale } = useI18n()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
|
||||
const automations = ref<Automation[]>([])
|
||||
const loading = ref(true)
|
||||
const query = ref('')
|
||||
const busy = ref(new Set<string>())
|
||||
const editorVisible = ref(false)
|
||||
const editing = ref<Automation | null>(null)
|
||||
const detailVisible = ref(false)
|
||||
const detail = ref<Automation | null>(null)
|
||||
const focusRunId = ref('')
|
||||
let loadVersion = 0
|
||||
let poll: ReturnType<typeof setTimeout> | undefined
|
||||
let disposed = false
|
||||
|
||||
const filtered = computed(() => {
|
||||
const q = query.value.trim().toLowerCase()
|
||||
if (!q) return automations.value
|
||||
return automations.value.filter((a) =>
|
||||
a.name.toLowerCase().includes(q) || a.instruction.toLowerCase().includes(q))
|
||||
})
|
||||
|
||||
function schedulePoll() {
|
||||
clearTimeout(poll)
|
||||
if (!disposed) poll = setTimeout(() => { void load(true) }, 5000)
|
||||
}
|
||||
|
||||
async function load(silent = false) {
|
||||
if (disposed) return
|
||||
clearTimeout(poll)
|
||||
const version = ++loadVersion
|
||||
try {
|
||||
const res = await listAutomations()
|
||||
if (version !== loadVersion) return
|
||||
automations.value = res.data ?? []
|
||||
if (detail.value) {
|
||||
const fresh = automations.value.find(item => item.id === detail.value?.id)
|
||||
if (fresh) detail.value = fresh
|
||||
else {
|
||||
detailVisible.value = false
|
||||
detail.value = null
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
if (version === loadVersion && !silent) MessagePlugin.error(e?.message || t('common.operationFailed'))
|
||||
} finally {
|
||||
if (version === loadVersion) {
|
||||
loading.value = false
|
||||
schedulePoll()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
useAssistantDataChange(() => { void load() }, { areas: ['automation'] })
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
++loadVersion
|
||||
clearTimeout(poll)
|
||||
})
|
||||
|
||||
function replace(item: Automation) {
|
||||
const index = automations.value.findIndex((a) => a.id === item.id)
|
||||
if (index >= 0) automations.value.splice(index, 1, item)
|
||||
else automations.value.unshift(item)
|
||||
if (detail.value?.id === item.id) detail.value = item
|
||||
}
|
||||
|
||||
function onSaved(item: Automation) {
|
||||
replace(item)
|
||||
void load(true)
|
||||
}
|
||||
|
||||
function openEditor(item: Automation | null) {
|
||||
editing.value = item
|
||||
detailVisible.value = false
|
||||
editorVisible.value = true
|
||||
}
|
||||
|
||||
function openDetail(item: Automation, runId = '') {
|
||||
detail.value = item
|
||||
focusRunId.value = runId
|
||||
detailVisible.value = true
|
||||
}
|
||||
|
||||
// Notifications link to /platform/automations/:id?run=…; the detail opens
|
||||
// over the list and the URL drops back to the list.
|
||||
async function openFromRoute() {
|
||||
const id = typeof route.params.automationId === 'string' ? route.params.automationId : ''
|
||||
if (!id) return
|
||||
const runId = typeof route.query.run === 'string' ? route.query.run : ''
|
||||
let item = automations.value.find((a) => a.id === id)
|
||||
if (!item) {
|
||||
try {
|
||||
item = (await getAutomation(id)).data
|
||||
} catch {
|
||||
MessagePlugin.warning(t('automation.messages.notFound'))
|
||||
}
|
||||
}
|
||||
if (item) openDetail(item, runId)
|
||||
const rest = { ...route.query }
|
||||
delete rest.run
|
||||
void router.replace({ name: 'automationList', query: rest })
|
||||
}
|
||||
|
||||
watch(() => route.params.automationId, () => {
|
||||
if (!loading.value) void openFromRoute()
|
||||
})
|
||||
|
||||
watch(detailVisible, (open) => {
|
||||
if (!open) focusRunId.value = ''
|
||||
})
|
||||
|
||||
async function toggle(item: Automation) {
|
||||
if (busy.value.has(item.id)) return
|
||||
if (hasEndedOnceSchedule(item)) {
|
||||
MessagePlugin.warning(t('automation.scheduleEndedHint'))
|
||||
return
|
||||
}
|
||||
busy.value.add(item.id)
|
||||
try {
|
||||
const res = item.enabled ? await pauseAutomation(item.id) : await resumeAutomation(item.id)
|
||||
onSaved(res.data)
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || t('common.operationFailed'))
|
||||
} finally {
|
||||
busy.value.delete(item.id)
|
||||
}
|
||||
}
|
||||
|
||||
async function runNow(item: Automation) {
|
||||
if (busy.value.has(item.id)) return
|
||||
busy.value.add(item.id)
|
||||
try {
|
||||
const res = await runAutomationNow(item.id)
|
||||
MessagePlugin.success(t('automation.messages.queued'))
|
||||
openDetail(item, res.data?.id ?? '')
|
||||
void load(true)
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || t('common.operationFailed'))
|
||||
} finally {
|
||||
busy.value.delete(item.id)
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(item: Automation) {
|
||||
if (busy.value.has(item.id)) return
|
||||
busy.value.add(item.id)
|
||||
try {
|
||||
await deleteAutomation(item.id)
|
||||
++loadVersion
|
||||
schedulePoll()
|
||||
automations.value = automations.value.filter((a) => a.id !== item.id)
|
||||
if (detail.value?.id === item.id) detailVisible.value = false
|
||||
MessagePlugin.success(t('common.deleteSuccess'))
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || t('common.deleteFailed'))
|
||||
} finally {
|
||||
busy.value.delete(item.id)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await load()
|
||||
await openFromRoute()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
@import (reference) '@/components/css/provider-card.less';
|
||||
@import (reference) '@/components/css/resource-card.less';
|
||||
|
||||
.automation-page {
|
||||
.resource-list-content();
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.automation-page__header {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
margin-bottom: 16px;
|
||||
flex-shrink: 0;
|
||||
|
||||
h2 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
font-family: var(--app-font-family);
|
||||
font-size: var(--app-text-4xl);
|
||||
font-weight: 600;
|
||||
line-height: 32px;
|
||||
}
|
||||
}
|
||||
|
||||
.automation-page__title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--app-space-4);
|
||||
}
|
||||
|
||||
.automation-page__tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.automation-page__search {
|
||||
width: 260px;
|
||||
max-width: 100%;
|
||||
|
||||
:deep(.t-input) {
|
||||
border-radius: var(--app-radius-sm);
|
||||
}
|
||||
}
|
||||
|
||||
.automation-page__add.t-button {
|
||||
flex-shrink: 0;
|
||||
min-height: 32px;
|
||||
padding: 0 12px;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: var(--td-bg-color-container);
|
||||
color: var(--td-text-color-primary);
|
||||
|
||||
:deep(.t-icon) {
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background: var(--td-bg-color-container-hover);
|
||||
border-color: var(--td-component-stroke);
|
||||
}
|
||||
}
|
||||
|
||||
.automation-page__subtitle {
|
||||
margin: 0;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-base);
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.automation-page__main {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
padding-bottom: var(--app-space-8);
|
||||
}
|
||||
|
||||
.loading-container {
|
||||
padding: 40px 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
padding: 80px 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.automation-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(min(100%, 320px), 1fr));
|
||||
gap: 10px;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.automation-card {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
padding: 12px;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-md);
|
||||
background: var(--td-bg-color-container);
|
||||
transition: background-color var(--app-motion-base) ease, box-shadow var(--app-motion-base) ease;
|
||||
|
||||
&:hover:not(.automation-card--add) {
|
||||
box-shadow: 0 3px 12px color-mix(in srgb, var(--td-text-color-primary) 6%, transparent);
|
||||
}
|
||||
|
||||
&.is-paused .automation-card__schedule {
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
&--add {
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
min-height: 112px;
|
||||
border-style: dashed;
|
||||
background: transparent;
|
||||
color: var(--td-text-color-placeholder);
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
text-align: center;
|
||||
|
||||
&:hover,
|
||||
&:focus-visible {
|
||||
color: var(--td-text-color-primary);
|
||||
border-color: var(--td-component-border);
|
||||
background: color-mix(in srgb, var(--td-bg-color-secondarycontainer) 15%, var(--td-bg-color-container));
|
||||
box-shadow: 0 3px 12px color-mix(in srgb, var(--td-text-color-primary) 5%, transparent);
|
||||
}
|
||||
|
||||
&__icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: var(--app-radius-md);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
font-size: var(--app-text-2xl);
|
||||
}
|
||||
|
||||
&__label {
|
||||
font-size: var(--app-text-md);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
&__hint {
|
||||
font-size: var(--app-text-xs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The whole card opens the detail; the buttons on it sit above this layer.
|
||||
.automation-card__open {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border: 0;
|
||||
border-radius: inherit;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.automation-card__header,
|
||||
.automation-card__footer,
|
||||
.automation-card__schedule,
|
||||
.automation-card__paused {
|
||||
position: relative;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.automation-card__actions,
|
||||
.automation-card__status {
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.automation-card__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-height: 28px;
|
||||
}
|
||||
|
||||
.automation-card__badge {
|
||||
.provider-card-badge(28px, 8px);
|
||||
}
|
||||
|
||||
.automation-card__title {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
font-size: var(--app-text-base);
|
||||
font-weight: 600;
|
||||
line-height: 20px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.automation-card__actions {
|
||||
display: flex;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.automation-card__icon-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: none;
|
||||
color: color-mix(in srgb, var(--td-text-color-primary) 55%, transparent);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
color: var(--td-text-color-secondary);
|
||||
background: color-mix(in srgb, var(--td-text-color-primary) 5%, transparent);
|
||||
}
|
||||
|
||||
&:active:not(:disabled) {
|
||||
background: color-mix(in srgb, var(--td-text-color-primary) 9%, transparent);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.4;
|
||||
}
|
||||
}
|
||||
|
||||
.automation-card__schedule,
|
||||
.automation-card__paused {
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.5;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.automation-card__paused {
|
||||
color: var(--td-warning-color);
|
||||
}
|
||||
|
||||
.automation-card__footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin-top: auto;
|
||||
}
|
||||
|
||||
.automation-card__meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px 8px;
|
||||
min-width: 0;
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-xs);
|
||||
}
|
||||
|
||||
.automation-card__status {
|
||||
flex-shrink: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 2px 4px;
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: none;
|
||||
color: var(--td-text-color-placeholder);
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-size: var(--app-text-sm);
|
||||
|
||||
&.is-enabled {
|
||||
color: var(--td-success-color);
|
||||
}
|
||||
|
||||
&.is-ended { cursor: default; }
|
||||
|
||||
&:hover:not(:disabled):not(.is-ended) {
|
||||
background: var(--td-bg-color-container-hover);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
cursor: wait;
|
||||
}
|
||||
}
|
||||
|
||||
.automation-card__dot {
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
border-radius: 50%;
|
||||
background: currentColor;
|
||||
}
|
||||
|
||||
.automation-card button:focus-visible,
|
||||
.automation-card--add:focus-visible {
|
||||
outline: 2px solid var(--td-text-color-secondary);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,50 @@
|
||||
<template>
|
||||
<span v-if="status && (status === 'succeeded' || iconOnly)" class="automation-status-icon" :class="`is-${status}`" role="img"
|
||||
:aria-label="t(`automation.status.${status}`)" :title="t(`automation.status.${status}`)">
|
||||
<t-icon :name="ICONS[status] || 'time'" size="16px" />
|
||||
</span>
|
||||
<t-tag v-else-if="status" size="small" variant="light" :theme="theme">{{ t(`automation.status.${status}`) }}</t-tag>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import type { AutomationRunStatus } from '@/api/automation'
|
||||
|
||||
const props = defineProps<{ status: AutomationRunStatus | 'paused' | ''; iconOnly?: boolean }>()
|
||||
const { t } = useI18n()
|
||||
|
||||
const ICONS: Record<string, string> = {
|
||||
succeeded: 'check-circle', failed: 'error-circle', running: 'loading', queued: 'time',
|
||||
awaiting_approval: 'secured', needs_attention: 'error-circle', cancelled: 'close-circle',
|
||||
skipped: 'jump', paused: 'pause-circle',
|
||||
}
|
||||
|
||||
const THEMES: Record<string, 'default' | 'primary' | 'success' | 'warning' | 'danger'> = {
|
||||
queued: 'default',
|
||||
running: 'primary',
|
||||
awaiting_approval: 'warning',
|
||||
succeeded: 'success',
|
||||
failed: 'danger',
|
||||
cancelled: 'default',
|
||||
skipped: 'default',
|
||||
needs_attention: 'warning',
|
||||
paused: 'default',
|
||||
}
|
||||
|
||||
const theme = computed(() => THEMES[props.status] ?? 'default')
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.automation-status-icon {
|
||||
display: inline-flex;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
color: var(--td-text-color-secondary);
|
||||
|
||||
&.is-succeeded { color: var(--td-success-color); }
|
||||
&.is-running { color: var(--td-brand-color); }
|
||||
&.is-failed { color: var(--td-error-color); }
|
||||
&.is-awaiting_approval, &.is-needs_attention { color: var(--td-warning-color); }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,427 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import test, { type TestContext } from 'node:test'
|
||||
import { compileScript, compileTemplate, parse } from '@vue/compiler-sfc'
|
||||
import * as vue from 'vue'
|
||||
import { change, fixture, flush } from '../../test-utils/vueFixture.ts'
|
||||
import * as schedule from '../../utils/automationSchedule.ts'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const useInputNumber = require('tdesign-vue-next/cjs/input-number/hooks/useInputNumber.js').default
|
||||
const numberProps = require('tdesign-vue-next/cjs/input-number/props.js').default
|
||||
|
||||
const automation = {
|
||||
id: 'automation-1', name: 'Reminder', instruction: 'Take a break',
|
||||
trigger: { type: 'cron', expr: '0 9 * * *', timezone: 'Asia/Shanghai' },
|
||||
approval_timeout_minutes: 1440, limits: { max_duration_minutes: 30 },
|
||||
enabled: true, session_mode: 'per_run', access_level: 'confirm',
|
||||
carry_last_result: false, misfire_policy: 'skip', overlap_policy: 'skip', notify_on_success: false,
|
||||
}
|
||||
|
||||
function setup(t: TestContext, file: string, api: Record<string, unknown>, props: Record<string, unknown>) {
|
||||
const f = fixture(t)
|
||||
const url = new URL(file, import.meta.url)
|
||||
const page = f.component(url, {
|
||||
'vue-i18n': { useI18n: () => ({ t: (key: string) => key, locale: vue.ref('en-US') }) },
|
||||
'vue-router': { useRoute: () => ({ params: {}, query: {} }), useRouter: () => ({ replace() {}, push() {} }) },
|
||||
'tdesign-vue-next': { MessagePlugin: { success() {}, error() {}, warning() {} } },
|
||||
'@/api/automation': api,
|
||||
'@/api/assistant': { ASSISTANT_ACCESS_LEVELS: ['read_only', 'confirm', 'auto_write'] },
|
||||
'@/stores/ui': { useUIStore: () => ({ openSettings() {} }) },
|
||||
'@/utils/automationSchedule': schedule,
|
||||
'@/composables/useModalShell': { useModalShell: () => ({ markClean() {}, requestClose() {} }) },
|
||||
}, props)
|
||||
const { descriptor } = parse(readFileSync(url, 'utf8'))
|
||||
const script = compileScript(descriptor, { id: 'automation-interactions' })
|
||||
const compiled = compileTemplate({
|
||||
source: descriptor.template!.content, filename: url.pathname, id: 'automation-interactions',
|
||||
compilerOptions: { bindingMetadata: script.bindings },
|
||||
})
|
||||
assert.deepEqual(compiled.errors, [])
|
||||
const { render } = f.evaluate(compiled.code, {
|
||||
vue: { ...vue, resolveComponent: (name: string) => name === 't-popup' ? { name } : name, resolveDynamicComponent: (name: string) => name,
|
||||
withCtx: (fn: unknown) => fn, withDirectives: (node: unknown) => node },
|
||||
})
|
||||
return { ...page, mount: f.mount, emit: f.emit, render: () => render(page.vm, [], props, page.vm, {}, {}) }
|
||||
}
|
||||
|
||||
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()) : []) : [])]
|
||||
}
|
||||
|
||||
test('assistant mutations refresh the automation list and open detail without replacing an editor draft', async t => {
|
||||
let items = [{ ...automation }]
|
||||
let calls = 0
|
||||
const { vm, emit, close } = setup(t, './AutomationList.vue', {
|
||||
listAutomations: async () => { calls++; return { data: items } },
|
||||
}, {})
|
||||
await flush()
|
||||
vm.openDetail(vm.automations[0])
|
||||
vm.query = 'Reminder'
|
||||
vm.editing = { ...automation, name: 'Unsaved draft' }
|
||||
vm.editorVisible = true
|
||||
items = [{ ...automation, name: 'Updated reminder', enabled: false }, { ...automation, id: 'new' }]
|
||||
emit(change('agent.update'))
|
||||
t.mock.timers.tick(300)
|
||||
assert.equal(calls, 1)
|
||||
emit(change('automation.create'))
|
||||
emit(change('automation.update'))
|
||||
emit(change('automation.pause'))
|
||||
t.mock.timers.tick(300)
|
||||
await flush()
|
||||
assert.equal(calls, 2, 'one request per burst')
|
||||
assert.equal(vm.automations.length, 2)
|
||||
assert.equal(vm.detail.name, 'Updated reminder')
|
||||
assert.equal(vm.detail.enabled, false)
|
||||
assert.equal(vm.detailVisible, true)
|
||||
assert.equal(vm.query, 'Reminder')
|
||||
assert.equal(vm.editing.name, 'Unsaved draft')
|
||||
assert.equal(vm.editorVisible, true)
|
||||
items = []
|
||||
emit(change('automation.delete'))
|
||||
t.mock.timers.tick(300)
|
||||
await flush()
|
||||
assert.equal(vm.detailVisible, false)
|
||||
assert.equal(vm.detail, null)
|
||||
close()
|
||||
emit(change('automation.create'))
|
||||
t.mock.timers.tick(300)
|
||||
assert.equal(calls, 3, 'unmounted pages unsubscribe')
|
||||
})
|
||||
|
||||
test('a stale automation list response cannot overwrite a newer assistant refresh', async t => {
|
||||
const requests: Array<(result: unknown) => void> = []
|
||||
const { vm, emit } = setup(t, './AutomationList.vue', {
|
||||
listAutomations: () => new Promise(resolve => requests.push(resolve)),
|
||||
}, {})
|
||||
emit(change('automation.update'))
|
||||
t.mock.timers.tick(300)
|
||||
assert.equal(requests.length, 2)
|
||||
requests[1]({ data: [{ ...automation, name: 'Fresh' }] })
|
||||
await flush()
|
||||
requests[0]({ data: [{ ...automation, name: 'Stale' }] })
|
||||
await flush()
|
||||
assert.equal(vm.automations[0].name, 'Fresh')
|
||||
})
|
||||
|
||||
test('assistant run-now refreshes idle history after any in-flight load and preserves earlier pages', async t => {
|
||||
let first!: (value: unknown) => void
|
||||
let calls = 0
|
||||
const oldRun = { id: 'old', status: 'succeeded', scheduled_at: '2026-10-20T10:00:00Z' }
|
||||
const newRun = { id: 'new', status: 'queued', scheduled_at: '2026-10-20T11:00:00Z' }
|
||||
const { vm, emit } = setup(t, './AutomationDetail.vue', {
|
||||
listAutomationRuns: () => ++calls === 1 ? new Promise(resolve => { first = resolve })
|
||||
: Promise.resolve({ data: [newRun, oldRun], total: 3 }),
|
||||
listAutomationGrants: async () => ({ data: [] }),
|
||||
listAutomationGrantCandidates: async () => ({ data: [] }),
|
||||
}, { visible: true, automation })
|
||||
emit(change('automation.run_now'))
|
||||
t.mock.timers.tick(300)
|
||||
assert.equal(calls, 1, 'wait for the initial page before merging newer runs')
|
||||
first({ data: [oldRun, { ...oldRun, id: 'earlier' }], total: 2 })
|
||||
await flush()
|
||||
assert.equal(calls, 2)
|
||||
assert.deepEqual(Array.from(vm.runs, (run: any) => run.id), ['new', 'old', 'earlier'])
|
||||
assert.equal(vm.runsTotal, 3)
|
||||
vm.instructionExpanded = true
|
||||
vm.$.props.automation = { ...automation, name: 'Updated name' }
|
||||
await vue.nextTick()
|
||||
assert.equal(calls, 2, 'refreshing the same automation does not reset loaded history')
|
||||
assert.equal(vm.instructionExpanded, true)
|
||||
vm.$.props.visible = false
|
||||
await vue.nextTick()
|
||||
emit(change('automation.run_now'))
|
||||
t.mock.timers.tick(300)
|
||||
assert.equal(calls, 2, 'closed detail does not fetch history')
|
||||
})
|
||||
|
||||
test('task content fades only while more text remains below the scroll position', async t => {
|
||||
const { vm, render } = setup(t, './AutomationDetail.vue', {},
|
||||
{ visible: false, automation })
|
||||
const scroller = vue.markRaw({ scrollHeight: 320, clientHeight: 160, scrollTop: 0 })
|
||||
vm.instructionScroller = scroller
|
||||
await vue.nextTick()
|
||||
const scrollNode = () => nodes(render()).find(node =>
|
||||
String(node.props?.class).includes('automation-detail__instruction-scroll'))
|
||||
const toggle = () => nodes(render()).find(node =>
|
||||
node.props?.class === 'automation-detail__instruction-toggle')
|
||||
assert.equal(vm.instructionHasMore, true)
|
||||
assert.match(scrollNode().props.class, /instruction-scroll--more/)
|
||||
assert.doesNotMatch(scrollNode().props.class, /instruction-scroll--expanded/)
|
||||
assert.equal(toggle().props['aria-expanded'], false)
|
||||
toggle().props.onClick()
|
||||
await vue.nextTick()
|
||||
assert.equal(scrollNode().props.style.maxHeight, 'none')
|
||||
assert.match(scrollNode().props.class, /instruction-scroll--expanded/)
|
||||
assert.equal(vm.instructionHasMore, false, 'expanded text is not faded')
|
||||
assert.equal(toggle().props['aria-expanded'], true)
|
||||
toggle().props.onClick()
|
||||
await vue.nextTick()
|
||||
assert.equal(scrollNode().props.style.maxHeight, '160px')
|
||||
assert.doesNotMatch(scrollNode().props.class, /instruction-scroll--expanded/)
|
||||
assert.equal(vm.instructionHasMore, true)
|
||||
|
||||
scroller.scrollTop = 160
|
||||
scrollNode().props.onScroll()
|
||||
assert.equal(vm.instructionHasMore, false, 'the last line is fully visible at the bottom')
|
||||
assert.doesNotMatch(scrollNode().props.class, /instruction-scroll--more/)
|
||||
|
||||
scroller.scrollTop = 50
|
||||
scrollNode().props.onScroll()
|
||||
assert.equal(vm.instructionHasMore, true)
|
||||
scroller.scrollHeight = 100
|
||||
scroller.scrollTop = 0
|
||||
vm.updateInstructionOverflow()
|
||||
assert.equal(vm.instructionHasMore, false, 'short content has no fade')
|
||||
assert.equal(toggle(), undefined, 'short content has no expand control')
|
||||
})
|
||||
|
||||
test('cards refresh live run states and return to the last result after completion', async t => {
|
||||
let state = { ...automation, active_run_status: '', last_run_status: 'succeeded' }
|
||||
let calls = 0
|
||||
const { vm, render, close } = setup(t, './AutomationList.vue', {
|
||||
listAutomations: async () => { calls++; return { data: [{ ...state }] } },
|
||||
}, {})
|
||||
await flush()
|
||||
const status = () => nodes(render()).find(node => node.props && 'status' in node.props)?.props.status
|
||||
assert.equal(status(), 'succeeded')
|
||||
vm.openDetail(vm.automations[0])
|
||||
vm.editing = { ...automation, name: 'Unsaved draft' }
|
||||
vm.editorVisible = true
|
||||
for (const active of ['queued', 'running', 'awaiting_approval', '']) {
|
||||
state = { ...state, active_run_status: active }
|
||||
t.mock.timers.tick(5000)
|
||||
await flush()
|
||||
assert.equal(status(), active || 'succeeded')
|
||||
assert.equal(vm.detail.active_run_status, active)
|
||||
assert.equal(vm.editing.name, 'Unsaved draft')
|
||||
assert.equal(vm.loading, false, 'background refresh keeps cards visible')
|
||||
}
|
||||
assert.equal(calls, 5)
|
||||
close()
|
||||
t.mock.timers.tick(15000)
|
||||
await flush()
|
||||
assert.equal(calls, 5, 'leaving the list stops polling')
|
||||
})
|
||||
|
||||
test('list polling waits for a slow response and does not restart after unmount', async t => {
|
||||
let resolve!: (value: unknown) => void
|
||||
let calls = 0
|
||||
const { close } = setup(t, './AutomationList.vue', {
|
||||
listAutomations: () => {
|
||||
calls++
|
||||
return new Promise(done => { resolve = done })
|
||||
},
|
||||
}, {})
|
||||
t.mock.timers.tick(15000)
|
||||
assert.equal(calls, 1, 'no overlapping polling requests')
|
||||
resolve({ data: [automation] })
|
||||
await flush()
|
||||
t.mock.timers.tick(5000)
|
||||
assert.equal(calls, 2)
|
||||
close()
|
||||
resolve({ data: [automation] })
|
||||
await flush()
|
||||
t.mock.timers.tick(15000)
|
||||
assert.equal(calls, 2)
|
||||
})
|
||||
|
||||
test('a stale poll cannot restore a deleted card and polling recovers from errors', async t => {
|
||||
let resolve!: (value: unknown) => void
|
||||
let calls = 0
|
||||
const { vm } = setup(t, './AutomationList.vue', {
|
||||
listAutomations: async () => {
|
||||
calls++
|
||||
if (calls === 1) return { data: [automation] }
|
||||
if (calls === 2) return new Promise(done => { resolve = done })
|
||||
if (calls === 3) throw new Error('Temporarily unavailable')
|
||||
return { data: [] }
|
||||
},
|
||||
deleteAutomation: async () => {},
|
||||
}, {})
|
||||
await flush()
|
||||
t.mock.timers.tick(5000)
|
||||
await vm.remove(vm.automations[0])
|
||||
resolve({ data: [automation] })
|
||||
await flush()
|
||||
assert.equal(vm.automations.length, 0)
|
||||
t.mock.timers.tick(5000)
|
||||
await flush()
|
||||
assert.equal(calls, 3)
|
||||
t.mock.timers.tick(5000)
|
||||
await flush()
|
||||
assert.equal(calls, 4)
|
||||
assert.equal(vm.automations.length, 0)
|
||||
})
|
||||
|
||||
test('approval hours update in both directions and save as minutes, without resetting on an empty edit', async t => {
|
||||
let saved: any
|
||||
const props = { visible: false, automation }
|
||||
const { vm, render, mount } = setup(t, './AutomationEditor.vue', {
|
||||
updateAutomation: async (_id: string, input: unknown) => { saved = input; return { data: automation } },
|
||||
validateAutomationTrigger: async () => ({ data: { next_runs: [] } }),
|
||||
}, props)
|
||||
vm.$.props.visible = true
|
||||
await vue.nextTick()
|
||||
assert.equal(vm.approvalHours, 24)
|
||||
const input = nodes(render()).find(node => node.type === 't-input-number' && node.props.max === 168)
|
||||
assert.ok(input)
|
||||
assert.equal(input.props.theme, 'row', 'both controls stay visible with full-sized click targets')
|
||||
assert.equal(input.props.suffix, undefined, 'the unit cannot crowd the numeric input or controls')
|
||||
// Use TDesign's real step handlers against the editor's compiled v-model binding.
|
||||
let control: any
|
||||
const NumberControl = vue.defineComponent({
|
||||
props: numberProps,
|
||||
setup(props) { control = useInputNumber(props); return () => null },
|
||||
})
|
||||
mount({ setup: () => () => vue.h(NumberControl,
|
||||
nodes(render()).find(node => node.type === 't-input-number' && node.props.max === 168).props) })
|
||||
control.handleAdd({})
|
||||
await vue.nextTick()
|
||||
assert.equal(vm.form.approval_timeout_minutes, 1500)
|
||||
assert.equal(control.userInput.value, '25')
|
||||
control.handleReduce({})
|
||||
await vue.nextTick()
|
||||
assert.equal(vm.form.approval_timeout_minutes, 1440)
|
||||
assert.equal(control.userInput.value, '24')
|
||||
const update = input.props['onUpdate:modelValue']
|
||||
update(undefined)
|
||||
assert.equal(vm.approvalHours, 24)
|
||||
update(0)
|
||||
assert.equal(vm.approvalHours, 1)
|
||||
update(169)
|
||||
assert.equal(vm.approvalHours, 168)
|
||||
update(4)
|
||||
await vm.save()
|
||||
assert.equal(saved.approval_timeout_minutes, 240)
|
||||
})
|
||||
|
||||
test('the editor preserves, changes, and clears an automation model override', async t => {
|
||||
const saved: any[] = []
|
||||
const { vm } = setup(t, './AutomationEditor.vue', {
|
||||
updateAutomation: async (_id: string, input: unknown) => { saved.push(input); return { data: automation } },
|
||||
validateAutomationTrigger: async () => ({ data: { next_runs: [] } }),
|
||||
}, { visible: false, automation: { ...automation, model_id: 'model-one' } })
|
||||
vm.$.props.visible = true
|
||||
await vue.nextTick()
|
||||
assert.equal(vm.form.model_id, 'model-one')
|
||||
vm.form.model_id = 'model-two'
|
||||
await vm.save()
|
||||
assert.equal(saved[0].model_id, 'model-two')
|
||||
vm.form.model_id = ''
|
||||
await vm.save()
|
||||
assert.equal(saved[1].model_id, '', 'clearing restores the assistant default instead of omitting the patch')
|
||||
})
|
||||
|
||||
test('list run and delete actions call APIs only after their inline confirmation', async t => {
|
||||
let runCalls = 0
|
||||
let deleteCalls = 0
|
||||
const { vm, render } = setup(t, './AutomationList.vue', {
|
||||
listAutomations: async () => ({ data: [{ ...automation, active_run_status: runCalls ? 'queued' : '' }] }),
|
||||
runAutomationNow: async () => { runCalls++; return { data: { id: 'run-1' } } },
|
||||
deleteAutomation: async () => { deleteCalls++ },
|
||||
}, {})
|
||||
await flush()
|
||||
const popups = nodes(render()).filter(node => node.type === 't-popconfirm')
|
||||
assert.equal(popups.length, 2)
|
||||
for (const popup of popups) {
|
||||
const trigger = nodes(popup).find(node => node.type === 'button')
|
||||
assert.ok(trigger)
|
||||
trigger.props.onClick?.()
|
||||
popup.props.onCancel?.()
|
||||
}
|
||||
assert.equal(runCalls, 0)
|
||||
assert.equal(deleteCalls, 0)
|
||||
await popups[0].props.onConfirm()
|
||||
await flush()
|
||||
assert.equal(runCalls, 1)
|
||||
assert.equal(vm.detailVisible, true)
|
||||
assert.equal(vm.automations[0].active_run_status, 'queued', 'manual runs refresh without waiting for the next poll')
|
||||
await popups[1].props.onConfirm()
|
||||
assert.equal(deleteCalls, 1)
|
||||
assert.equal(vm.automations.length, 0)
|
||||
})
|
||||
|
||||
test('run history groups by the automation timezone and drawer run requires confirmation', async t => {
|
||||
let runCalls = 0
|
||||
const props = { visible: false, automation }
|
||||
const { vm, render } = setup(t, './AutomationDetail.vue', {
|
||||
runAutomationNow: async () => { runCalls++; return { data: { id: 'new-run' } } },
|
||||
}, props)
|
||||
vm.runs = [
|
||||
{ id: 'a', scheduled_at: '2026-10-20T16:30:00Z' },
|
||||
{ id: 'b', scheduled_at: '2026-10-20T16:00:00Z' },
|
||||
{ id: 'c', scheduled_at: '2026-10-20T15:59:00Z' },
|
||||
].map(run => ({ ...run, status: 'succeeded', session_id: 'chat', trigger_kind: 'schedule' }))
|
||||
assert.equal(vm.runGroups.length, 2)
|
||||
assert.equal(vm.runGroups[0].date, 'October 21, 2026')
|
||||
assert.equal(vm.runGroups[0].runs.length, 2)
|
||||
assert.equal(vm.runTime(vm.runs[0].scheduled_at), '00:30')
|
||||
const popup = nodes(render()).find(node => node.type === 't-popconfirm')
|
||||
assert.ok(popup)
|
||||
const trigger = nodes(popup).find(node => node.type === 'button')
|
||||
assert.equal(trigger.props['aria-label'], 'automation.actions.runNow')
|
||||
trigger.props.onClick?.()
|
||||
assert.equal(runCalls, 0)
|
||||
await popup.props.onConfirm()
|
||||
assert.equal(runCalls, 1)
|
||||
})
|
||||
|
||||
test('grant popup preserves history and dismisses when starting a run or reopening the drawer', async t => {
|
||||
const { vm, render } = setup(t, './AutomationDetail.vue', {
|
||||
listAutomationGrants: async () => ({ data: [] }),
|
||||
listAutomationGrantCandidates: async () => ({ data: [{ prompt_id: 'approval-1', label: 'Update document', risk: 'write' }] }),
|
||||
listAutomationRuns: async () => ({ data: [], total: 0 }),
|
||||
runAutomationNow: async () => ({ data: { id: 'new-run' } }),
|
||||
}, { visible: false, automation })
|
||||
assert.equal(vm.grantsVisible, false)
|
||||
const popup = nodes(render()).find(node => node.type?.name === 't-popup')
|
||||
popup.props['onUpdate:visible'](true)
|
||||
assert.equal(vm.grantsVisible, true)
|
||||
await vm.loadGrants()
|
||||
assert.equal(vm.grantsVisible, true, 'loading grants must not dismiss their popup')
|
||||
const trigger = nodes(render()).find(node => node.type === 'button' && node.props?.class?.includes('automation-detail__grants-trigger'))
|
||||
assert.ok(trigger.props.class.includes('is-attention'), 'candidates remain visible from the trigger')
|
||||
assert.equal(trigger.props['aria-expanded'], true)
|
||||
assert.ok(nodes(render()).some(node => node.props?.class === 'automation-detail__history'))
|
||||
await vm.runNow()
|
||||
assert.equal(vm.grantsVisible, false, 'a manual run dismisses the popup to reveal progress')
|
||||
assert.equal(vm.runs[0].id, 'new-run')
|
||||
popup.props['onUpdate:visible'](true)
|
||||
vm.$.props.visible = true
|
||||
await flush()
|
||||
assert.equal(vm.grantsVisible, false, 'reopening the drawer does not restore a stale popup')
|
||||
})
|
||||
|
||||
for (const file of ['./AutomationList.vue', './AutomationDetail.vue']) {
|
||||
test(`${file}: elapsed one-shot schedules have no resume entry, but manual run remains available`, async t => {
|
||||
let resumeCalls = 0
|
||||
const item = { ...automation, enabled: false, trigger: { type: 'once', at: new Date(Date.now() - 60_000).toISOString() } }
|
||||
const { vm, render } = setup(t, file, {
|
||||
listAutomations: async () => ({ data: [item] }),
|
||||
resumeAutomation: async () => { resumeCalls++; return { data: { ...item, enabled: true } } },
|
||||
}, { visible: false, automation: item })
|
||||
await flush()
|
||||
const resumeButton = () => nodes(render()).find(node => node.type === 'button'
|
||||
&& (node.props?.role === 'switch' || node.props?.['aria-label'] === 'automation.actions.resume'))
|
||||
assert.equal(resumeButton(), undefined)
|
||||
assert.ok(nodes(render()).some(node => node.type === 't-popconfirm'
|
||||
&& node.props?.['confirm-btn']?.content === 'automation.actions.runNow'))
|
||||
await vm.toggle(item)
|
||||
assert.equal(resumeCalls, 0, 'stale handlers cannot resume an elapsed schedule')
|
||||
|
||||
item.trigger.at = new Date(Date.now() + 60_000).toISOString()
|
||||
assert.ok(resumeButton(), 'a paused future one-shot can still be resumed')
|
||||
if (file.includes('Detail')) {
|
||||
assert.ok(nodes(render()).some(node => node.props?.name === 'resume'), 'resume uses its own icon')
|
||||
}
|
||||
await vm.toggle(item)
|
||||
assert.equal(resumeCalls, 1)
|
||||
})
|
||||
}
|
||||
@@ -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 <script>/)
|
||||
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 <script>/)
|
||||
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',
|
||||
'AcademyDocResult.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, /<script>/)
|
||||
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_academy_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, /<script>/)
|
||||
assert.doesNotMatch(search, /javascript:|fallback-output|<script>/)
|
||||
|
||||
const read = await render({
|
||||
displayType: 'read_academy_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 = 'academy-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, /<script>/)
|
||||
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 Academy 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 === 'Academy' },
|
||||
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 Academy 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, 'Academy')
|
||||
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.', 'Academy')
|
||||
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 === 'Academy')
|
||||
|
||||
// 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 Academy 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"
|
||||
/>
|
||||
|
||||
<AcademyDocResult
|
||||
v-else-if="displayType === 'search_academy_docs' || displayType === 'read_academy_doc'"
|
||||
:mode="displayType === 'read_academy_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 AcademyDocResult from './tool-results/AcademyDocResult.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,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.academyDocs.pages', { count: pages.length })
|
||||
: $t('agentStream.academyDocs.hits', { count: hits.length }) }}
|
||||
</div>
|
||||
<p v-if="!rows.length" class="doc-empty">{{ $t('agentStream.academyDocs.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.academyDocs.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.academyDocs.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.academyDocs.content') }}</div>
|
||||
<DocMarkdown :source="read.content" />
|
||||
<p v-if="read.truncated" class="doc-note">{{ $t('agentStream.academyDocs.truncated') }}</p>
|
||||
</div>
|
||||
<p v-else-if="!read.outline.length && !read.error" class="doc-empty">{{ $t('agentStream.academyDocs.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.academyDocs.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,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"> ({{ doc.file_type }})</template>
|
||||
<template v-if="doc.file_size"> · {{ 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,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>
|
||||
@@ -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 })
|
||||
})
|
||||
@@ -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), '')
|
||||
})
|
||||
@@ -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')
|
||||
}
|
||||
}
|
||||
@@ -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'])
|
||||
})
|
||||
Loaded 100 of 5767 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user