chore: 项目基线(基于 WeKnora 定制版,整理文件忽略规则)
This commit is contained in:
commit
9097ee699d
5769 files changed
+1446466
No files matched your search
@@ -0,0 +1,196 @@
|
||||
<template>
|
||||
<t-popup v-model:visible="open" trigger="click" placement="top-left"
|
||||
:overlay-inner-style="{ padding: '4px', borderRadius: 'var(--app-radius-lg)' }">
|
||||
<button type="button" class="assistant-access-trigger" :class="`is-${assistant.effectiveAccessLevel}`"
|
||||
:aria-label="`${t('assistant.access.title')}: ${t(`assistant.access.levels.${assistant.effectiveAccessLevel}.label`)}`"
|
||||
aria-haspopup="menu" :aria-expanded="open" @keydown.esc="open = false">
|
||||
<t-icon :name="LEVEL_ICONS[assistant.effectiveAccessLevel]" class="assistant-access-trigger__icon" />
|
||||
<span class="assistant-access-trigger__label">
|
||||
{{ t(`assistant.access.levels.${assistant.effectiveAccessLevel}.label`) }}
|
||||
</span>
|
||||
<svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor" class="assistant-access-trigger__arrow"
|
||||
:class="{ rotate: open }" aria-hidden="true">
|
||||
<path d="M2.5 4.5L6 8L9.5 4.5H2.5Z" />
|
||||
</svg>
|
||||
</button>
|
||||
<template #content>
|
||||
<div class="assistant-access-menu" role="menu" :aria-label="t('assistant.access.title')"
|
||||
@keydown.esc="open = false">
|
||||
<div class="assistant-access-menu__title" role="presentation">{{ t('assistant.access.title') }}</div>
|
||||
<button v-for="level in ASSISTANT_ACCESS_LEVELS" :key="level" type="button" role="menuitemradio"
|
||||
class="assistant-access-option" :class="{ selected: level === assistant.effectiveAccessLevel }"
|
||||
:aria-checked="level === assistant.effectiveAccessLevel" :disabled="!allowed(level)"
|
||||
@click="pick(level)">
|
||||
<t-icon :name="LEVEL_ICONS[level]" class="assistant-access-option__icon" />
|
||||
<span class="assistant-access-option__text">
|
||||
<span class="assistant-access-option__label">{{ t(`assistant.access.levels.${level}.label`) }}</span>
|
||||
<span class="assistant-access-option__desc">
|
||||
{{ allowed(level) ? t(`assistant.access.levels.${level}.desc`) : t('assistant.access.capped') }}
|
||||
</span>
|
||||
</span>
|
||||
<t-icon v-if="level === assistant.effectiveAccessLevel" name="check" size="14px"
|
||||
class="assistant-access-option__check" />
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
</t-popup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useAssistantStore } from '@/stores/assistant'
|
||||
import {
|
||||
ASSISTANT_ACCESS_LEVELS,
|
||||
capAssistantAccessLevel,
|
||||
type AssistantAccessLevel,
|
||||
} from '@/api/assistant'
|
||||
|
||||
const LEVEL_ICONS: Record<AssistantAccessLevel, string> = {
|
||||
read_only: 'browse',
|
||||
confirm: 'secured',
|
||||
auto_write: 'edit',
|
||||
}
|
||||
|
||||
const { t } = useI18n()
|
||||
const assistant = useAssistantStore()
|
||||
const open = ref(false)
|
||||
|
||||
const allowed = (level: AssistantAccessLevel) => capAssistantAccessLevel(level, assistant.accessCeiling) === level
|
||||
|
||||
function pick(level: AssistantAccessLevel) {
|
||||
if (!allowed(level)) return
|
||||
assistant.setAccessLevel(level)
|
||||
open.value = false
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.assistant-access-trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
flex-shrink: 0;
|
||||
height: 28px;
|
||||
padding: 0 8px;
|
||||
box-sizing: border-box;
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: transparent;
|
||||
color: var(--td-text-color-secondary);
|
||||
font: inherit;
|
||||
font-size: var(--app-text-sm);
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: background var(--app-motion-instant);
|
||||
|
||||
&:hover {
|
||||
background: var(--td-bg-color-secondarycontainer-hover);
|
||||
}
|
||||
|
||||
// The level that acts without asking stands out, so it is never on by accident.
|
||||
&.is-auto_write {
|
||||
color: var(--td-warning-color);
|
||||
}
|
||||
}
|
||||
|
||||
.assistant-access-trigger__icon {
|
||||
font-size: var(--app-text-base);
|
||||
}
|
||||
|
||||
.assistant-access-trigger__label {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.assistant-access-trigger__arrow {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
color: var(--td-text-color-placeholder);
|
||||
transition: transform var(--app-motion-instant);
|
||||
|
||||
&.rotate {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
}
|
||||
|
||||
.assistant-access-menu {
|
||||
width: 260px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.assistant-access-menu__title {
|
||||
padding: 6px 8px;
|
||||
margin-bottom: 2px;
|
||||
border-bottom: .5px solid var(--td-component-stroke);
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-sm);
|
||||
font-weight: 500;
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.assistant-access-option {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
padding: 6px 8px;
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: transparent;
|
||||
color: var(--td-text-color-primary);
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover:not(:disabled), &:focus-visible {
|
||||
background: var(--td-bg-color-secondarycontainer-hover);
|
||||
}
|
||||
|
||||
&.selected {
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
cursor: not-allowed;
|
||||
color: var(--td-text-color-disabled);
|
||||
}
|
||||
}
|
||||
|
||||
.assistant-access-option__icon {
|
||||
flex-shrink: 0;
|
||||
margin-top: 2px;
|
||||
font-size: var(--app-text-base);
|
||||
color: var(--td-text-color-secondary);
|
||||
|
||||
.assistant-access-option:disabled & {
|
||||
color: inherit;
|
||||
}
|
||||
}
|
||||
|
||||
.assistant-access-option__text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.assistant-access-option__label {
|
||||
font-size: var(--app-text-sm);
|
||||
font-weight: 500;
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.assistant-access-option__desc {
|
||||
font-size: var(--app-text-xs);
|
||||
line-height: 16px;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.assistant-access-option__check {
|
||||
flex-shrink: 0;
|
||||
margin-top: 3px;
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
</style>
|
||||
@@ -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 ts from 'typescript'
|
||||
|
||||
const source = readFileSync(new URL('./AssistantContextChip.vue', import.meta.url), 'utf8')
|
||||
const { descriptor } = parse(source)
|
||||
const script = compileScript(descriptor, { id: 'context-chip-test' }).content
|
||||
|
||||
test('agent breadcrumb uses its name and falls back to the id', () => {
|
||||
const assistant = vue.reactive({
|
||||
pageContext: { agentId: 'agent-a', agentName: 'Agent A' } as any, contextAttached: true,
|
||||
})
|
||||
const dependencies: Record<string, unknown> = {
|
||||
vue, 'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
|
||||
'@/stores/assistant': { useAssistantStore: () => assistant },
|
||||
}
|
||||
const exports: any = {}
|
||||
runInNewContext(ts.transpileModule(script, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS },
|
||||
}).outputText, { exports, require: (name: string) => dependencies[name] })
|
||||
const state = exports.default.setup({}, { expose() {} })
|
||||
assert.deepEqual(Array.from(state.segments.value), ['Agent A'])
|
||||
assistant.pageContext.agentName = ''
|
||||
assert.deepEqual(Array.from(state.segments.value), ['agent-a'])
|
||||
assistant.pageContext = { knowledgeBaseId: 'kb', knowledgeBaseName: 'KB', knowledgeTitle: 'Doc', knowledgeId: 'doc' }
|
||||
assert.deepEqual(Array.from(state.segments.value), ['KB', 'Doc'])
|
||||
})
|
||||
|
||||
test('settings and chat breadcrumbs name the page and the open resource', () => {
|
||||
const assistant = vue.reactive({ pageContext: { page: 'settings_models' } as any, contextAttached: true })
|
||||
const exports: any = {}
|
||||
runInNewContext(ts.transpileModule(script, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS },
|
||||
}).outputText, {
|
||||
exports,
|
||||
require: (name: string) => ({
|
||||
vue, 'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
|
||||
'@/stores/assistant': { useAssistantStore: () => assistant },
|
||||
} as Record<string, unknown>)[name],
|
||||
})
|
||||
const state = exports.default.setup({}, { expose() {} })
|
||||
assert.deepEqual(Array.from(state.segments.value), ['assistant.context.pages.settings_models'])
|
||||
assistant.pageContext = { page: 'settings_models', modelId: 'm-1', modelName: 'Qwen' }
|
||||
assert.deepEqual(Array.from(state.segments.value), ['assistant.context.pages.settings_models', 'Qwen'])
|
||||
assistant.pageContext = { page: 'mcp_services', mcpServiceId: 'mcp-1' }
|
||||
assert.deepEqual(Array.from(state.segments.value), ['assistant.context.pages.mcp_services', 'mcp-1'])
|
||||
assistant.pageContext = { page: 'chat', chatSessionId: 's', messageId: 'msg' }
|
||||
assert.deepEqual(Array.from(state.segments.value), ['assistant.context.chatMessage'])
|
||||
assistant.pageContext = { page: 'knowledge_base', knowledgeBaseId: 'kb', knowledgeBaseName: 'KB' }
|
||||
assert.deepEqual(Array.from(state.segments.value), ['KB'], 'a knowledge base keeps its own breadcrumb')
|
||||
})
|
||||
|
||||
test('a dialog open over the page shows under the page', () => {
|
||||
const assistant = vue.reactive({
|
||||
pageContext: { knowledgeBaseId: 'kb', knowledgeBaseName: 'KB', knowledgeTitle: 'Doc', knowledgeId: 'doc' } as any,
|
||||
pageView: 'Edit Markdown', contextAttached: true,
|
||||
})
|
||||
const exports: any = {}
|
||||
runInNewContext(ts.transpileModule(script, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS },
|
||||
}).outputText, {
|
||||
exports,
|
||||
require: (name: string) => ({
|
||||
vue, 'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
|
||||
'@/stores/assistant': { useAssistantStore: () => assistant },
|
||||
} as Record<string, unknown>)[name],
|
||||
})
|
||||
const state = exports.default.setup({}, { expose() {} })
|
||||
assert.deepEqual(Array.from(state.segments.value), ['KB', 'Edit Markdown'])
|
||||
assistant.pageContext = null
|
||||
assert.deepEqual(Array.from(state.segments.value), ['Edit Markdown'], 'a dialog alone is enough')
|
||||
assistant.pageView = ''
|
||||
assert.deepEqual(Array.from(state.segments.value), [])
|
||||
})
|
||||
|
||||
test('a page that publishes nothing shows its route title', () => {
|
||||
const assistant = vue.reactive({
|
||||
pageContext: null as any, pageTitle: 'Toolbox / Skills', pageView: '', contextAttached: true,
|
||||
})
|
||||
const exports: any = {}
|
||||
runInNewContext(ts.transpileModule(script, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS },
|
||||
}).outputText, {
|
||||
exports,
|
||||
require: (name: string) => ({
|
||||
vue, 'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
|
||||
'@/stores/assistant': { useAssistantStore: () => assistant },
|
||||
} as Record<string, unknown>)[name],
|
||||
})
|
||||
const state = exports.default.setup({}, { expose() {} })
|
||||
assert.deepEqual(Array.from(state.segments.value), ['Toolbox', 'Skills'])
|
||||
assistant.pageTitle = 'Agents'
|
||||
assistant.pageView = 'Agents / Tools'
|
||||
assert.deepEqual(Array.from(state.segments.value), ['Agents', 'Tools'], 'the page is not repeated')
|
||||
assistant.pageTitle = ''
|
||||
assistant.pageView = 'Settings / Models'
|
||||
assert.deepEqual(Array.from(state.segments.value), ['Settings', 'Models'])
|
||||
assistant.pageContext = { agentId: 'a', agentName: 'Helper' }
|
||||
assistant.pageTitle = 'Agents'
|
||||
assistant.pageView = ''
|
||||
assert.deepEqual(Array.from(state.segments.value), ['Helper'], 'a published context wins over the title')
|
||||
})
|
||||
@@ -0,0 +1,128 @@
|
||||
<template>
|
||||
<div class="assistant-context-chip" :class="{ 'is-detached': !assistant.contextAttached }">
|
||||
<t-icon name="window" class="assistant-context-chip__icon" aria-hidden="true" />
|
||||
<span class="assistant-context-chip__label">{{ t(segments.length && !assistant.contextAttached
|
||||
? 'assistant.context.detachedLabel' : 'assistant.context.currentPage') }}</span>
|
||||
<span class="assistant-context-chip__sep" aria-hidden="true">·</span>
|
||||
<t-tooltip :content="tooltip" placement="top">
|
||||
<span class="assistant-context-chip__path">{{ segments.join(' / ') || '—' }}</span>
|
||||
</t-tooltip>
|
||||
<button v-if="segments.length" type="button" class="assistant-context-chip__toggle"
|
||||
:aria-label="assistant.contextAttached ? t('assistant.context.detach') : tooltip"
|
||||
:title="assistant.contextAttached ? t('assistant.context.detach') : tooltip"
|
||||
@click.stop="assistant.contextAttached ? assistant.dismissPageContext() : assistant.restorePageContext()">
|
||||
<t-icon :name="assistant.contextAttached ? 'close' : 'add'" size="12px" />
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useAssistantStore } from '@/stores/assistant'
|
||||
|
||||
const { t } = useI18n()
|
||||
const assistant = useAssistantStore()
|
||||
const context = computed(() => assistant.pageContext)
|
||||
const view = computed(() => assistant.pageView)
|
||||
|
||||
const segments = computed(() => {
|
||||
const base = pageSegments()
|
||||
if (!view.value) return base
|
||||
// The page stays as the parent of the dialog open over it, once.
|
||||
const parent = base.slice(0, 1)
|
||||
const viewParts = view.value.split(' / ')
|
||||
return viewParts[0] === parent[0] ? [...parent, ...viewParts.slice(1)] : [...parent, ...viewParts]
|
||||
})
|
||||
|
||||
function pageSegments(): string[] {
|
||||
const c = context.value
|
||||
if (!c) return assistant.pageTitle ? assistant.pageTitle.split(' / ') : []
|
||||
if (c.messageId) return [t('assistant.context.chatMessage')]
|
||||
if (c.modelId) return [t('assistant.context.pages.settings_models'), c.modelName || c.modelId]
|
||||
if (c.mcpServiceId) return [t('assistant.context.pages.mcp_services'), c.mcpServiceName || c.mcpServiceId]
|
||||
if (c.agentId) return [c.agentName || c.agentId]
|
||||
if (!c.knowledgeBaseId && c.page) return [t(`assistant.context.pages.${c.page}`)]
|
||||
const leaf = c.wikiTitle || c.wikiSlug || c.knowledgeTitle
|
||||
const path = [c.knowledgeBaseName, leaf].filter((s): s is string => !!s)
|
||||
return path.length ? path : [t('assistant.context.currentPage')]
|
||||
}
|
||||
|
||||
const tooltip = computed(() => {
|
||||
const path = segments.value.join(' / ')
|
||||
if (!path) return t('assistant.context.currentPage')
|
||||
return assistant.contextAttached
|
||||
? t('assistant.context.attachedTip', { path })
|
||||
: t('assistant.context.detachedTip', { path })
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.assistant-context-chip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
height: 28px;
|
||||
box-sizing: border-box;
|
||||
font-size: var(--app-text-sm, 13px);
|
||||
line-height: 20px;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.assistant-context-chip__icon {
|
||||
flex-shrink: 0;
|
||||
font-size: var(--app-text-base);
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.assistant-context-chip__label {
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.assistant-context-chip__path {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--td-text-color-primary);
|
||||
|
||||
.is-detached & {
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
}
|
||||
|
||||
.assistant-context-chip__sep {
|
||||
flex-shrink: 0;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.assistant-context-chip__toggle {
|
||||
appearance: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: transparent;
|
||||
color: var(--td-text-color-placeholder);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
background: var(--td-bg-color-container-hover);
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--td-brand-color-focus);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,159 @@
|
||||
<template>
|
||||
<t-popup v-model:visible="open" trigger="click" placement="top-left"
|
||||
:overlay-inner-style="{ padding: '4px', borderRadius: 'var(--app-radius-lg)' }">
|
||||
<button type="button" class="assistant-context-trigger" :aria-label="t('assistant.context.currentPage')"
|
||||
:title="t('assistant.context.currentPage')" aria-haspopup="dialog" :aria-expanded="open"
|
||||
@keydown.esc="open = false">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
||||
stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<path d="M12 4v16M4 12h16" />
|
||||
</svg>
|
||||
</button>
|
||||
<template #content>
|
||||
<div class="assistant-context-menu" role="dialog" :aria-label="t('assistant.context.currentPage')"
|
||||
@keydown.esc="open = false">
|
||||
<div class="assistant-context-menu__page">
|
||||
<AssistantContextChip />
|
||||
</div>
|
||||
<button type="button" role="switch" class="assistant-context-menu__access"
|
||||
:aria-label="t('assistant.access.page.label')" :aria-checked="assistant.pageAccess"
|
||||
@click="assistant.setPageAccess(!assistant.pageAccess)">
|
||||
<t-icon name="window" class="assistant-context-menu__icon" aria-hidden="true" />
|
||||
<span class="assistant-context-menu__text">
|
||||
<span class="assistant-context-menu__label">{{ t('assistant.access.page.label') }}</span>
|
||||
<span class="assistant-context-menu__desc">{{ t('assistant.access.page.desc') }}</span>
|
||||
</span>
|
||||
<span class="assistant-context-menu__switch" :class="{ 'is-on': assistant.pageAccess }" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
</t-popup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useAssistantStore } from '@/stores/assistant'
|
||||
import AssistantContextChip from './AssistantContextChip.vue'
|
||||
|
||||
const { t } = useI18n()
|
||||
const assistant = useAssistantStore()
|
||||
const open = ref(false)
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.assistant-context-trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
font: inherit;
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: transparent;
|
||||
color: var(--td-text-color-secondary);
|
||||
cursor: pointer;
|
||||
transition: background var(--app-motion-instant), color var(--app-motion-instant);
|
||||
user-select: none;
|
||||
|
||||
&:hover, &[aria-expanded='true'] {
|
||||
background: var(--td-bg-color-secondarycontainer-hover);
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--td-brand-color-focus);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
}
|
||||
|
||||
.assistant-context-menu {
|
||||
width: 300px;
|
||||
max-width: calc(100vw - 40px);
|
||||
}
|
||||
|
||||
.assistant-context-menu__page {
|
||||
display: flex;
|
||||
padding: 6px 8px;
|
||||
margin-bottom: 4px;
|
||||
border-bottom: .5px solid var(--td-component-stroke);
|
||||
}
|
||||
|
||||
.assistant-context-menu__access {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
padding: 8px;
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: transparent;
|
||||
color: var(--td-text-color-primary);
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover, &:focus-visible {
|
||||
background: var(--td-bg-color-secondarycontainer-hover);
|
||||
}
|
||||
}
|
||||
|
||||
.assistant-context-menu__icon {
|
||||
flex-shrink: 0;
|
||||
margin-top: 2px;
|
||||
font-size: var(--app-text-base);
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.assistant-context-menu__text {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.assistant-context-menu__label {
|
||||
font-size: var(--app-text-sm);
|
||||
font-weight: 500;
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.assistant-context-menu__desc {
|
||||
font-size: var(--app-text-xs);
|
||||
line-height: 16px;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.assistant-context-menu__switch {
|
||||
flex-shrink: 0;
|
||||
width: 28px;
|
||||
height: 16px;
|
||||
margin-top: 2px;
|
||||
border-radius: var(--app-radius-md);
|
||||
background: var(--td-bg-color-component);
|
||||
transition: background var(--app-motion-fast);
|
||||
|
||||
&::after {
|
||||
content: '';
|
||||
display: block;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
margin: 2px;
|
||||
border-radius: 50%;
|
||||
background: var(--td-text-color-anti);
|
||||
transition: transform var(--app-motion-fast);
|
||||
}
|
||||
|
||||
&.is-on {
|
||||
background: var(--td-brand-color);
|
||||
|
||||
&::after {
|
||||
transform: translateX(12px);
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,63 @@
|
||||
<template>
|
||||
<!-- On the right edge, where the panel opens, clear of the upload progress
|
||||
card in the bottom-right corner. -->
|
||||
<button v-if="assistant.entry === 'launcher' && !assistant.visible" type="button" class="assistant-launcher"
|
||||
:aria-label="name" @click="assistant.open()">
|
||||
<t-icon name="compass" class="assistant-launcher__icon" />
|
||||
<span class="assistant-launcher__label">{{ name }}</span>
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useAssistantStore } from '@/stores/assistant'
|
||||
|
||||
const { t } = useI18n()
|
||||
const assistant = useAssistantStore()
|
||||
const name = computed(() => assistant.displayName || t('assistant.title'))
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.assistant-launcher {
|
||||
position: fixed;
|
||||
top: 50%;
|
||||
right: 0;
|
||||
z-index: 1400;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
max-width: 36px;
|
||||
height: 36px;
|
||||
padding: 0 10px;
|
||||
box-sizing: border-box;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-right: 0;
|
||||
border-radius: var(--app-radius-lg) 0 0 var(--app-radius-lg);
|
||||
background: var(--td-bg-color-container);
|
||||
box-shadow: var(--td-shadow-1);
|
||||
color: var(--td-brand-color);
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
transform: translateY(-50%);
|
||||
transition: max-width var(--app-motion-base) ease, box-shadow var(--app-motion-fast) ease;
|
||||
|
||||
&:hover, &:focus-visible {
|
||||
max-width: 200px;
|
||||
box-shadow: var(--td-shadow-2);
|
||||
}
|
||||
}
|
||||
|
||||
.assistant-launcher__icon {
|
||||
flex-shrink: 0;
|
||||
font-size: var(--app-text-lg);
|
||||
}
|
||||
|
||||
.assistant-launcher__label {
|
||||
font-size: var(--app-text-sm);
|
||||
font-weight: 500;
|
||||
color: var(--td-text-color-primary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,46 @@
|
||||
<template>
|
||||
<AssistantSelectionBubble />
|
||||
<PageFillNotice />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onUnmounted, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { useAssistantStore } from '@/stores/assistant'
|
||||
import { routeTitle } from '@/utils/assistantRouteTitle'
|
||||
import { installPageAwareness } from '@/utils/pageAwareness'
|
||||
import AssistantSelectionBubble from './AssistantSelectionBubble.vue'
|
||||
import PageFillNotice from './PageFillNotice.vue'
|
||||
|
||||
// What the assistant sees of the page beside it: the page, the open dialog
|
||||
// and the selection feed its input box; its edits show up on the page.
|
||||
const assistant = useAssistantStore()
|
||||
const route = useRoute()
|
||||
const { t, locale } = useI18n()
|
||||
let uninstall: (() => void) | null = null
|
||||
|
||||
watch(() => [route.name, route.params.section, locale.value], () => {
|
||||
assistant.setPageTitle(routeTitle(route, t))
|
||||
}, { immediate: true })
|
||||
|
||||
// With page access off the assistant sees nothing of the page, this included.
|
||||
let view = ''
|
||||
onMounted(() => {
|
||||
uninstall = installPageAwareness({
|
||||
onView: next => {
|
||||
view = next
|
||||
assistant.setPageView(assistant.pageAccess ? next : '')
|
||||
},
|
||||
onSelection: selection => assistant.setPageSelection(assistant.pageAccess ? selection : null),
|
||||
})
|
||||
})
|
||||
watch(() => assistant.pageAccess, on => {
|
||||
assistant.setPageView(on ? view : '')
|
||||
if (!on) assistant.setPageSelection(null)
|
||||
})
|
||||
onUnmounted(() => {
|
||||
uninstall?.()
|
||||
assistant.setPageTitle('')
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,548 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import test from 'node:test'
|
||||
import { compileScript, parse } from '@vue/compiler-sfc'
|
||||
import * as vue from 'vue'
|
||||
import * as pinia from 'pinia'
|
||||
import ts from 'typescript'
|
||||
import * as childAgentTabs from '../../composables/useChildAgentTabs'
|
||||
|
||||
const filename = fileURLToPath(new URL('./AssistantPanel.vue', import.meta.url))
|
||||
const { descriptor } = parse(readFileSync(filename, 'utf8'), { filename })
|
||||
const panelScript = compileScript(descriptor, { id: 'assistant-panel-test', inlineTemplate: true }).content
|
||||
const storeScript = readFileSync(new URL('../../stores/assistant.ts', import.meta.url), 'utf8')
|
||||
const groupingScript = readFileSync(new URL('../sessionGrouping.ts', import.meta.url), 'utf8')
|
||||
const assistantApiScript = readFileSync(new URL('../../api/assistant.ts', import.meta.url), 'utf8')
|
||||
|
||||
function evaluate(source: string, dependencies: Record<string, unknown>, globals = {}) {
|
||||
const exports: any = {}
|
||||
runInNewContext(ts.transpileModule(source, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText, {
|
||||
exports, console, ...globals,
|
||||
require(name: string) {
|
||||
if (name in dependencies) return dependencies[name]
|
||||
throw new Error(`Unexpected component dependency: ${name}`)
|
||||
},
|
||||
})
|
||||
return exports
|
||||
}
|
||||
|
||||
function storage() {
|
||||
const values = new Map<string, string>()
|
||||
return {
|
||||
getItem: (key: string) => values.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => { values.set(key, value) },
|
||||
removeItem: (key: string) => { values.delete(key) },
|
||||
}
|
||||
}
|
||||
|
||||
const flush = async () => {
|
||||
await new Promise(resolve => setImmediate(resolve))
|
||||
await vue.nextTick()
|
||||
}
|
||||
|
||||
async function fixture(
|
||||
createSession: (data?: any) => Promise<any> = async () => ({ data: { id: 'new-session' } }),
|
||||
workspaceConfig = { display_name: '', max_access_level: 'confirm' },
|
||||
api: Record<string, (...args: any[]) => Promise<any>> = {},
|
||||
) {
|
||||
let workspaceRefreshes = 0
|
||||
let workspaceChanged: (() => void) | undefined
|
||||
const auth = vue.reactive({ user: { id: 'user-a' }, effectiveTenantId: 1, refreshFromAuthMe: async () => { workspaceRefreshes++; return true } })
|
||||
const assistantApi = evaluate(assistantApiScript, {
|
||||
'@/utils/request': { get: async () => ({ success: true, data: workspaceConfig }), put: assert.fail },
|
||||
})
|
||||
const sessionStorage = storage()
|
||||
sessionStorage.setItem('weknora:assistant-session:user-a:2', 'workspace-b-session')
|
||||
sessionStorage.setItem('weknora:assistant-session:user-b:1', 'user-b-session')
|
||||
const localStorage = storage()
|
||||
const stores = evaluate(storeScript, {
|
||||
vue, pinia, './auth': { useAuthStore: () => auth }, '@/api/assistant': assistantApi,
|
||||
}, { sessionStorage, localStorage })
|
||||
const storeRoot = pinia.createPinia()
|
||||
pinia.setActivePinia(storeRoot)
|
||||
const assistant = stores.useAssistantStore()
|
||||
const mounted: Array<{ sessionId: string; query: string }> = []
|
||||
const sent: Array<{ sessionId: string; query: string; scope: any }> = []
|
||||
const menuEntries: unknown[] = []
|
||||
const errors: string[] = []
|
||||
const dialogs: any[] = []
|
||||
const listCalls: any[][] = []
|
||||
const deleted: string[] = []
|
||||
const emptyComponent = vue.defineComponent({ inheritAttrs: false, render: () => null })
|
||||
const ChatView = vue.defineComponent({
|
||||
inheritAttrs: false,
|
||||
props: ['session_id', 'initialQuery', 'hostScope'],
|
||||
setup(props) {
|
||||
vue.onMounted(() => {
|
||||
mounted.push({ sessionId: props.session_id, query: props.initialQuery })
|
||||
// ChatView sends initialQuery on mount and reads hostScope during send.
|
||||
if (props.initialQuery) {
|
||||
sent.push({ sessionId: props.session_id, query: props.initialQuery, scope: props.hostScope() })
|
||||
}
|
||||
})
|
||||
return () => null
|
||||
},
|
||||
})
|
||||
const component = evaluate(panelScript, {
|
||||
vue,
|
||||
'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
|
||||
'tdesign-vue-next': {
|
||||
MessagePlugin: { error: (message: string) => errors.push(message) },
|
||||
DialogPlugin: { confirm: (options: any) => { dialogs.push(options); return { destroy() {} } } },
|
||||
},
|
||||
'@/views/chat/index.vue': ChatView,
|
||||
'@/views/chat/components/ChildAgentTabBar.vue': emptyComponent,
|
||||
'@/composables/useChildAgentTabs': childAgentTabs,
|
||||
'@/components/Input-field.vue': emptyComponent,
|
||||
'@/components/PanelResizeHandle.vue': emptyComponent,
|
||||
'./AssistantContextMenu.vue': emptyComponent,
|
||||
'./AssistantSelectionChip.vue': emptyComponent,
|
||||
'./AssistantAccessPicker.vue': emptyComponent,
|
||||
'@/api/chat': {
|
||||
createSessions: createSession,
|
||||
getSession: api.getSession || (async () => ({ success: true, data: { kind: 'assistant' } })),
|
||||
getSessionsList: async (...args: any[]) => {
|
||||
listCalls.push(args)
|
||||
return api.getSessionsList ? api.getSessionsList(...args) : { success: true, data: [], total: 0 }
|
||||
},
|
||||
},
|
||||
'@/components/sessionGrouping': evaluate(groupingScript, {}),
|
||||
'@/api/agent': { BUILTIN_WEKNORA_ASSISTANT_ID: 'builtin-weknora-assistant' },
|
||||
'@/stores/menu': { useMenuStore: () => ({ updataMenuChildren: (entry: unknown) => menuEntries.push(entry) }) },
|
||||
'@/stores/auth': { useAuthStore: () => auth },
|
||||
'@/stores/assistant': stores,
|
||||
'@/utils/assistantDataChange': { useAssistantDataChange: (callback: () => void, options: { areas: string[] }) => {
|
||||
assert.deepEqual(Array.from(options.areas), ['workspace'])
|
||||
workspaceChanged = callback
|
||||
} },
|
||||
'@/components/sessionMutations': {
|
||||
SESSION_MUTATION_EVENT: 'session-mutation',
|
||||
removeSession: async (id: string) => {
|
||||
if (api.removeSession) await api.removeSession(id)
|
||||
deleted.push(id)
|
||||
},
|
||||
},
|
||||
}, { window: { addEventListener() {}, removeEventListener() {} } }).default
|
||||
type HostNode = { children: HostNode[]; parent?: HostNode; tag?: string; props: Record<string, any>; style: Record<string, any>; text?: string }
|
||||
const node = (tag?: string): HostNode => ({ children: [], tag, props: {}, style: {} })
|
||||
const remove = (child: HostNode) => {
|
||||
if (child.parent) child.parent.children.splice(child.parent.children.indexOf(child), 1)
|
||||
child.parent = undefined
|
||||
}
|
||||
const renderer = vue.createRenderer<HostNode, HostNode>({
|
||||
createElement: node, createText: node, createComment: node,
|
||||
insert(child, parent, anchor) {
|
||||
remove(child)
|
||||
const index = anchor ? parent.children.indexOf(anchor) : -1
|
||||
parent.children.splice(index < 0 ? parent.children.length : index, 0, child)
|
||||
child.parent = parent
|
||||
},
|
||||
remove, setElementText(node, text) { node.text = text }, setText(node, text) { node.text = text },
|
||||
patchProp(node, key, _prev, next) { node.props[key] = next },
|
||||
parentNode: child => child.parent ?? null,
|
||||
nextSibling: child => child.parent?.children[child.parent.children.indexOf(child) + 1] ?? null,
|
||||
})
|
||||
const app = renderer.createApp(component)
|
||||
app.use(storeRoot)
|
||||
// The panel keeps its content mounted while hidden, which is essential to this regression.
|
||||
app.component('t-icon', emptyComponent)
|
||||
app.component('t-loading', emptyComponent)
|
||||
app.component('t-tooltip', vue.defineComponent({ inheritAttrs: false, setup: (_, { slots }) => () => slots.default?.() }))
|
||||
app.component('t-button', vue.defineComponent({ setup: (_, { slots }) => () => vue.h('button', slots.default?.()) }))
|
||||
const root = node()
|
||||
app.mount(root)
|
||||
const findAll = (predicate: (node: HostNode) => boolean): HostNode[] => {
|
||||
const found: HostNode[] = []
|
||||
const walk = (node: HostNode) => {
|
||||
if (predicate(node)) found.push(node)
|
||||
node.children.forEach(walk)
|
||||
}
|
||||
walk(root)
|
||||
return found
|
||||
}
|
||||
const click = async (label: string) => {
|
||||
const button = findAll(node => node.props['aria-label'] === label)[0]
|
||||
assert.ok(button, `missing button ${label}`)
|
||||
button.props.onClick()
|
||||
await flush()
|
||||
}
|
||||
await flush()
|
||||
return { workspaceChanged: () => workspaceChanged?.(), workspaceRefreshes: () => workspaceRefreshes, auth, assistant, mounted, sent, menuEntries, sessionStorage, localStorage, findAll, click, listCalls, deleted, dialogs, errors, close: () => app.unmount() }
|
||||
}
|
||||
|
||||
test('layout and width persist, with the width kept within bounds', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
assert.equal(f.assistant.layout, 'docked')
|
||||
f.assistant.setLayout('floating')
|
||||
assert.equal(f.localStorage.getItem('weknora:assistant-layout'), 'floating')
|
||||
f.assistant.setWidth(10_000)
|
||||
assert.equal(f.assistant.width, 760)
|
||||
f.assistant.setWidth(12)
|
||||
assert.equal(f.assistant.width, 360)
|
||||
assert.equal(f.localStorage.getItem('weknora:assistant-width'), '360')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('a run asks for the chosen access level, capped by the workspace ceiling', async () => {
|
||||
const f = await fixture(undefined, { display_name: ' Kora ', max_access_level: 'confirm' })
|
||||
try {
|
||||
assert.equal(f.assistant.displayName, 'Kora')
|
||||
f.assistant.setAccessLevel('auto_write')
|
||||
assert.equal(f.assistant.effectiveAccessLevel, 'confirm')
|
||||
f.assistant.open({ query: 'Clean up the wiki' })
|
||||
await flush()
|
||||
assert.equal(f.sent[0].scope.assistantAccess, 'confirm')
|
||||
f.assistant.setWorkspaceConfig({ display_name: '', max_access_level: 'auto_write' })
|
||||
assert.equal(f.assistant.effectiveAccessLevel, 'auto_write', 'raising the ceiling restores the choice')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
for (const identity of ['workspace', 'user']) {
|
||||
test(`restoring another ${identity}'s session does not resend the old first message`, async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
f.assistant.publishPageContext(Symbol(), { knowledgeBaseId: 'kb-a', wikiIssueIds: ['issue-1', 'issue-2'] })
|
||||
f.assistant.open({ query: 'Fix this issue', focus: { wikiIssueIds: ['issue-2'] } })
|
||||
await flush()
|
||||
assert.equal(f.sent.length, 1)
|
||||
assert.equal(f.sent[0].query, 'Fix this issue')
|
||||
assert.deepEqual(Array.from(f.sent[0].scope.pageContext.wiki_issue_ids), ['issue-2'])
|
||||
f.assistant.close()
|
||||
if (identity === 'workspace') f.auth.effectiveTenantId = 2
|
||||
else f.auth.user = { id: 'user-b' }
|
||||
await flush()
|
||||
const restored = identity === 'workspace' ? 'workspace-b-session' : 'user-b-session'
|
||||
assert.deepEqual(f.mounted.at(-1), { sessionId: restored, query: '' })
|
||||
assert.equal(f.sent.length, 1, 'restoring a session must load history instead of sending')
|
||||
f.assistant.open()
|
||||
await flush()
|
||||
assert.equal(f.sent.length, 1, 'reopening the retained panel must not resend either')
|
||||
} finally { f.close() }
|
||||
})
|
||||
}
|
||||
|
||||
test('a new conversation still sends its own first message after restoring a session', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
f.auth.effectiveTenantId = 2
|
||||
await flush()
|
||||
f.assistant.open({ query: 'New request' })
|
||||
await flush()
|
||||
assert.equal(f.sent.length, 1)
|
||||
assert.equal(f.sent[0].sessionId, 'new-session')
|
||||
assert.equal(f.sent[0].query, 'New request')
|
||||
assert.equal(f.sessionStorage.getItem('weknora:assistant-session:user-a:2'), 'new-session')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('session creation finishing after a workspace switch cannot replace the restored session', async () => {
|
||||
let resolve!: (value: { data: { id: string } }) => void
|
||||
const f = await fixture(() => new Promise(done => { resolve = done }))
|
||||
try {
|
||||
f.assistant.open({ query: 'Old workspace request' })
|
||||
await flush()
|
||||
f.auth.effectiveTenantId = 2
|
||||
await flush()
|
||||
resolve({ data: { id: 'old-workspace-session' } })
|
||||
await flush()
|
||||
assert.equal(f.assistant.sessionId, 'workspace-b-session')
|
||||
assert.equal(f.sessionStorage.getItem('weknora:assistant-session:user-a:2'), 'workspace-b-session')
|
||||
assert.equal(f.sent.length, 0)
|
||||
assert.equal(f.menuEntries.length, 0)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('assistant creation marks the kind and never inserts a sidebar entry', async () => {
|
||||
const requests: any[] = []
|
||||
const f = await fixture(async body => {
|
||||
requests.push(body)
|
||||
return { data: { id: 'assistant-session' } }
|
||||
})
|
||||
try {
|
||||
f.assistant.open({ query: 'Help me' })
|
||||
await flush()
|
||||
assert.equal(requests.length, 1)
|
||||
assert.equal(requests[0].kind, 'assistant')
|
||||
assert.equal(f.menuEntries.length, 0)
|
||||
assert.equal(f.sent[0].sessionId, 'assistant-session')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('history loads, paginates, highlights and switches the current session', async () => {
|
||||
const f = await fixture(undefined, undefined, {
|
||||
getSessionsList: async page => ({
|
||||
success: true, total: 21,
|
||||
data: Array.from({ length: page === 1 ? 20 : 1 }, (_, i) => ({
|
||||
id: `history-${(page - 1) * 20 + i}`, title: '', updated_at: new Date().toISOString(),
|
||||
})),
|
||||
}),
|
||||
})
|
||||
try {
|
||||
f.assistant.setSession('history-0')
|
||||
await flush()
|
||||
await f.click('assistant.history')
|
||||
assert.deepEqual(f.listCalls[0], [1, 20, undefined, 'assistant'])
|
||||
assert.equal(f.mounted.length, 1, 'history keeps the current transcript mounted')
|
||||
assert.equal(f.findAll(n => n.props.class?.includes('is-current')).length, 1)
|
||||
assert.equal(f.findAll(n => n.text === 'assistant.untitledConversation').length, 20)
|
||||
const loadMore = f.findAll(n => n.tag === 'button' && n.props.onClick && n.props.variant === 'text')[0]
|
||||
loadMore.props.onClick()
|
||||
await flush()
|
||||
assert.deepEqual(f.listCalls[1], [2, 20, undefined, 'assistant'])
|
||||
const rows = f.findAll(n => n.props.class === 'assistant-history__select')
|
||||
assert.equal(rows.length, 21)
|
||||
rows[20].props.onClick()
|
||||
await flush()
|
||||
assert.equal(f.assistant.sessionId, 'history-20')
|
||||
assert.equal(f.mounted.at(-1)?.sessionId, 'history-20')
|
||||
assert.equal(f.sent.length, 0)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('deleting the current history session requires confirmation and returns to welcome', async () => {
|
||||
const f = await fixture(undefined, undefined, {
|
||||
getSessionsList: async () => ({ success: true, total: 1, data: [{ id: 'current', title: 'Current' }] }),
|
||||
})
|
||||
try {
|
||||
f.assistant.setSession('current')
|
||||
await flush()
|
||||
await f.click('assistant.history')
|
||||
await f.click('common.delete')
|
||||
assert.equal(f.deleted.length, 0)
|
||||
await f.dialogs[0].onConfirm()
|
||||
await flush()
|
||||
assert.deepEqual(f.deleted, ['current'])
|
||||
assert.equal(f.assistant.sessionId, '')
|
||||
assert.equal(f.sessionStorage.getItem('weknora:assistant-session:user-a:1'), null)
|
||||
assert.equal(f.findAll(n => n.props.class === 'assistant-welcome').length, 1)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
for (const status of [403, 404, 500]) {
|
||||
test(`stored session load with HTTP ${status} handles stale ids without mounting a transcript`, async () => {
|
||||
const f = await fixture(undefined, undefined, {
|
||||
getSession: async () => { throw { $httpStatus: status } },
|
||||
})
|
||||
try {
|
||||
f.auth.effectiveTenantId = 2
|
||||
await flush()
|
||||
assert.equal(f.assistant.sessionId, status === 500 ? 'workspace-b-session' : '')
|
||||
assert.equal(f.mounted.length, 0)
|
||||
if (status === 500) assert.equal(f.findAll(n => n.props.role === 'alert').length, 1)
|
||||
} finally { f.close() }
|
||||
})
|
||||
}
|
||||
|
||||
test('stored ordinary session is rejected instead of mounting it as assistant history', async () => {
|
||||
const f = await fixture(undefined, undefined, {
|
||||
getSession: async () => ({ success: true, data: { id: 'workspace-b-session', kind: '' } }),
|
||||
})
|
||||
try {
|
||||
f.auth.effectiveTenantId = 2
|
||||
await flush()
|
||||
assert.equal(f.assistant.sessionId, '')
|
||||
assert.equal(f.sessionStorage.getItem('weknora:assistant-session:user-a:2'), null)
|
||||
assert.equal(f.mounted.length, 0)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('history distinguishes empty and failed loads and retries the same page', async () => {
|
||||
let failed = true
|
||||
const f = await fixture(undefined, undefined, {
|
||||
getSessionsList: async () => {
|
||||
if (failed) throw new Error('offline')
|
||||
return { success: true, total: 0, data: [] }
|
||||
},
|
||||
})
|
||||
try {
|
||||
await f.click('assistant.history')
|
||||
assert.equal(f.findAll(n => n.props.role === 'alert').length, 1)
|
||||
failed = false
|
||||
f.findAll(n => n.tag === 'button' && n.props.variant === 'text')[0].props.onClick()
|
||||
await flush()
|
||||
assert.equal(f.listCalls[1][0], 1)
|
||||
assert.equal(f.findAll(n => n.text === 'assistant.historyEmpty').length, 1)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('a history response from the previous workspace is discarded', async () => {
|
||||
let resolve!: (value: any) => void
|
||||
const f = await fixture(undefined, undefined, {
|
||||
getSessionsList: () => new Promise(done => { resolve = done }),
|
||||
})
|
||||
try {
|
||||
await f.click('assistant.history')
|
||||
f.auth.effectiveTenantId = 2
|
||||
await flush()
|
||||
resolve({ success: true, total: 1, data: [{ id: 'private' }] })
|
||||
await flush()
|
||||
assert.equal(f.findAll(n => n.props.class === 'assistant-history__select').length, 0)
|
||||
assert.equal(f.assistant.sessionId, 'workspace-b-session')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('failed history deletion retains the conversation and reports the error', async () => {
|
||||
const f = await fixture(undefined, undefined, {
|
||||
getSessionsList: async () => ({ success: true, total: 1, data: [{ id: 'current' }] }),
|
||||
removeSession: async () => { throw new Error('offline') },
|
||||
})
|
||||
try {
|
||||
f.assistant.setSession('current')
|
||||
await flush()
|
||||
await f.click('assistant.history')
|
||||
await f.click('common.delete')
|
||||
await f.dialogs[0].onConfirm()
|
||||
await flush()
|
||||
assert.equal(f.assistant.sessionId, 'current')
|
||||
assert.deepEqual(f.errors, ['chat.deleteSessionFailed'])
|
||||
assert.equal(f.findAll(n => n.props.class === 'assistant-history__select').length, 1)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('a pending delete confirmation cannot delete a session after switching workspaces', async () => {
|
||||
const f = await fixture(undefined, undefined, {
|
||||
getSessionsList: async () => ({ success: true, total: 1, data: [{ id: 'old' }] }),
|
||||
})
|
||||
try {
|
||||
await f.click('assistant.history')
|
||||
await f.click('common.delete')
|
||||
f.auth.effectiveTenantId = 2
|
||||
await flush()
|
||||
await f.dialogs[0].onConfirm()
|
||||
assert.deepEqual(f.deleted, [])
|
||||
assert.equal(f.assistant.sessionId, 'workspace-b-session')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('agent layers merge, dismissal follows the agent id, and the payload has no KB', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
const owner = Symbol()
|
||||
const nested = Symbol()
|
||||
f.assistant.publishPageContext(owner, { agentId: 'agent-a', agentName: 'A' })
|
||||
f.assistant.publishPageContext(nested, { agentName: 'Edited' })
|
||||
assert.equal(f.assistant.pageContext.agentName, 'Edited')
|
||||
f.assistant.retractPageContext(nested)
|
||||
assert.equal(f.assistant.pageContext.agentName, 'A')
|
||||
f.assistant.dismissPageContext()
|
||||
assert.equal(f.assistant.contextAttached, false)
|
||||
f.assistant.publishPageContext(owner, { agentId: 'agent-b', agentName: 'B' })
|
||||
assert.equal(f.assistant.contextAttached, true)
|
||||
f.assistant.open({ query: 'Check this agent' })
|
||||
await flush()
|
||||
assert.equal(f.sent[0].scope.pageContext.agent_id, 'agent-b')
|
||||
assert.equal(f.sent[0].scope.knowledgeBaseIds.length, 0)
|
||||
assert.equal(f.sent[0].scope.pageContext.knowledge_base_id, undefined)
|
||||
f.assistant.publishPageContext(nested, { knowledgeBaseId: 'kb-a' })
|
||||
assert.equal(f.assistant.pageContext.agentId, 'agent-b')
|
||||
assert.equal(f.assistant.pageContext.knowledgeBaseId, 'kb-a')
|
||||
f.assistant.retractPageContext(owner)
|
||||
assert.equal(f.assistant.pageContext.knowledgeBaseId, 'kb-a')
|
||||
f.assistant.retractPageContext(nested)
|
||||
assert.equal(f.assistant.pageContext, null)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('settings and chat pages send their resources without widening the search scope', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
const owner = Symbol()
|
||||
f.assistant.publishPageContext(owner, { page: 'chat', chatSessionId: 'chat-1', messageId: 'msg-1' })
|
||||
f.assistant.open({ query: 'Why this answer?' })
|
||||
await flush()
|
||||
assert.equal(f.sent.length, 1)
|
||||
assert.deepEqual(Array.from(f.sent[0].scope.knowledgeBaseIds), [])
|
||||
assert.equal(JSON.stringify(f.sent[0].scope.pageContext),
|
||||
JSON.stringify({ page: 'chat', session_id: 'chat-1', message_id: 'msg-1' }))
|
||||
|
||||
f.assistant.publishPageContext(owner, { page: 'settings_models', section: 'chat', modelId: 'm-1', messageId: 'stale' })
|
||||
assert.ok(f.assistant.pageContext)
|
||||
f.assistant.open({ query: 'Check it' })
|
||||
await flush()
|
||||
assert.equal(JSON.stringify(f.sent.at(-1)?.scope.pageContext),
|
||||
JSON.stringify({ page: 'settings_models', section: 'chat', model_id: 'm-1' }),
|
||||
'a message without its session is not sent')
|
||||
|
||||
f.assistant.publishPageContext(owner, { section: 'tools' })
|
||||
assert.equal(f.assistant.pageContext, null, 'a section alone names no page')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('the open dialog and the selection go with the message, the selection only once', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
const owner = Symbol()
|
||||
f.assistant.publishPageContext(owner, { knowledgeBaseId: 'kb-a', knowledgeBaseName: 'KB' })
|
||||
f.assistant.setPageView('Edit Markdown')
|
||||
f.assistant.setPageSelection({ text: 'Run setup.', field: 'Content', ref: 'e2', startLine: 7, endLine: 7 })
|
||||
f.assistant.open({ query: 'Polish this' })
|
||||
await flush()
|
||||
assert.deepEqual(Array.from(f.sent[0].scope.knowledgeBaseIds), [],
|
||||
'the current page must not become an explicit KB selection')
|
||||
assert.equal(JSON.stringify(f.sent[0].scope.pageContext), JSON.stringify({
|
||||
knowledge_base_id: 'kb-a', view: 'Edit Markdown',
|
||||
selection: { text: 'Run setup.', field: 'Content', ref: 'e2', start_line: 7, end_line: 7 },
|
||||
}))
|
||||
assert.equal(f.assistant.pageSelection, null, 'the selection is used up by the message')
|
||||
|
||||
f.assistant.retractPageContext(owner)
|
||||
f.assistant.setPageView('')
|
||||
f.assistant.setPageSelection({ text: 'page text' })
|
||||
f.assistant.open({ query: 'Explain' })
|
||||
await flush()
|
||||
assert.equal(JSON.stringify(f.sent.at(-1)?.scope.pageContext), JSON.stringify({ selection: { text: 'page text' } }),
|
||||
'a selection alone is a page context')
|
||||
|
||||
f.assistant.setPageView('Edit Markdown')
|
||||
f.assistant.dismissPageContext()
|
||||
assert.equal(f.assistant.contextAttached, false)
|
||||
f.assistant.setPageView('Another dialog')
|
||||
assert.equal(f.assistant.contextAttached, true, 'a new dialog brings the context back')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('a page that publishes nothing still sends its route title', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
f.assistant.setPageTitle('Agents')
|
||||
assert.equal(f.assistant.contextAttached, true)
|
||||
f.assistant.open({ query: 'What is here?' })
|
||||
await flush()
|
||||
assert.equal(JSON.stringify(f.sent.at(-1)?.scope.pageContext), JSON.stringify({ title: 'Agents' }))
|
||||
|
||||
f.assistant.dismissPageContext()
|
||||
assert.equal(f.assistant.contextAttached, false)
|
||||
f.assistant.setPageTitle('Toolbox')
|
||||
assert.equal(f.assistant.contextAttached, true, 'another page brings it back')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('ask sends into the open conversation and starts one when there is none', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
f.assistant.ask('First')
|
||||
await flush()
|
||||
assert.equal(f.sent.at(-1)?.query, 'First')
|
||||
assert.equal(f.assistant.queuedMessage, null)
|
||||
f.assistant.ask('Second')
|
||||
assert.equal(f.assistant.queuedMessage?.query, 'Second', 'the open conversation sends it')
|
||||
assert.equal(f.assistant.takeQueuedMessage()?.query, 'Second')
|
||||
assert.equal(f.assistant.queuedMessage, null)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('workspace changes refresh the shared profile and workspace selector even while the panel is hidden', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
assert.equal(f.assistant.visible, false)
|
||||
assert.equal(f.workspaceRefreshes(), 0)
|
||||
f.workspaceChanged()
|
||||
await flush()
|
||||
assert.equal(f.workspaceRefreshes(), 1)
|
||||
} finally { f.close() }
|
||||
})
|
||||
@@ -0,0 +1,737 @@
|
||||
<template>
|
||||
<!-- Hidden with a class, not v-if, so a reply keeps streaming while closed. -->
|
||||
<aside class="assistant-panel" :class="[`is-${effectiveLayout}`, { 'is-open': assistant.visible, 'is-resizing': resizing }]"
|
||||
:style="{ width: `${panelWidth}px` }" role="complementary" :aria-label="assistantName"
|
||||
:aria-hidden="!assistant.visible">
|
||||
<PanelResizeHandle edge="left" :label="t('assistant.resize')" :value="panelWidth"
|
||||
:min="ASSISTANT_PANEL_MIN_WIDTH" :max="ASSISTANT_PANEL_MAX_WIDTH"
|
||||
@start="startResize" @resize="resize" @end="resizing = false" />
|
||||
|
||||
<header class="assistant-panel__header">
|
||||
<ChildAgentTabBar header-mode :tabs="childTabs.tabs.value"
|
||||
:active-id="childTabs.activeId.value" :attention="childTabs.attention.value"
|
||||
@select="selectConversationTab" @close="childTabs.close">
|
||||
<template #parent>
|
||||
<span class="assistant-panel__header-icon" aria-hidden="true"><t-icon name="compass" /></span>
|
||||
<span class="assistant-panel__title">{{ assistantName }}</span>
|
||||
</template>
|
||||
</ChildAgentTabBar>
|
||||
<t-tooltip :content="t('assistant.newConversation')" placement="bottom">
|
||||
<button type="button" class="assistant-panel__action" :disabled="!assistant.sessionId || starting"
|
||||
:aria-label="t('assistant.newConversation')" @click="startNewConversation">
|
||||
<t-icon name="chat-add" size="16px" />
|
||||
</button>
|
||||
</t-tooltip>
|
||||
<t-tooltip :content="t('assistant.history')" placement="bottom">
|
||||
<button type="button" class="assistant-panel__action" :aria-label="t('assistant.history')"
|
||||
:aria-pressed="showHistory" @click="toggleHistory">
|
||||
<t-icon name="history" size="16px" />
|
||||
</button>
|
||||
</t-tooltip>
|
||||
<t-tooltip v-if="canDock" :content="layoutToggleLabel" placement="bottom">
|
||||
<button type="button" class="assistant-panel__action" :aria-label="layoutToggleLabel"
|
||||
:aria-pressed="assistant.layout === 'docked'" @click="toggleLayout">
|
||||
<t-icon :name="assistant.layout === 'docked' ? 'pin-filled' : 'pin'" size="16px" />
|
||||
</button>
|
||||
</t-tooltip>
|
||||
<t-tooltip :content="t('common.close')" placement="bottom">
|
||||
<button type="button" class="assistant-panel__action" :aria-label="t('common.close')"
|
||||
@click="assistant.close()">
|
||||
<t-icon name="close" size="16px" />
|
||||
</button>
|
||||
</t-tooltip>
|
||||
</header>
|
||||
|
||||
<div class="assistant-panel__body">
|
||||
<div v-if="showHistory" class="assistant-history">
|
||||
<div v-for="session in history" :key="session.id" class="assistant-history__row"
|
||||
:class="{ 'is-current': session.id === assistant.sessionId }">
|
||||
<button type="button" class="assistant-history__select" @click="selectSession(session.id)">
|
||||
<span>{{ session.title || t('assistant.untitledConversation') }}</span>
|
||||
<small>{{ t(`time.${classifyDateBucket(session.updated_at || session.created_at)}`) }}</small>
|
||||
</button>
|
||||
<t-tooltip :content="t('common.delete')">
|
||||
<button type="button" class="assistant-panel__action" :aria-label="t('common.delete')"
|
||||
:disabled="deleting === session.id" @click="confirmDelete(session.id)">
|
||||
<t-icon name="delete" size="16px" />
|
||||
</button>
|
||||
</t-tooltip>
|
||||
</div>
|
||||
<p v-if="historyError" role="alert">{{ t('assistant.historyFailed') }}</p>
|
||||
<p v-else-if="!historyLoading && !history.length">{{ t('assistant.historyEmpty') }}</p>
|
||||
<t-button v-if="historyError || history.length < historyTotal" variant="text" block
|
||||
:loading="historyLoading" @click="loadHistory()">
|
||||
{{ historyError ? t('common.retry') : t('assistant.loadMore') }}
|
||||
</t-button>
|
||||
<t-loading v-else-if="historyLoading" size="small" />
|
||||
</div>
|
||||
<div v-show="!showHistory" class="assistant-panel__conversation">
|
||||
<ChatView v-if="assistant.sessionId && readySessionId === assistant.sessionId"
|
||||
:key="assistant.sessionId" :session_id="assistant.sessionId"
|
||||
:agent-id="BUILTIN_WEKNORA_ASSISTANT_ID" :embedded-mode="true" :initial-query="initialQuery"
|
||||
:host-scope="hostScope" :model-id="assistant.modelId" :default-model-id="defaultModelId"
|
||||
@update:model-id="assistant.setModel">
|
||||
<template v-if="assistant.pageSelection" #composer-chips>
|
||||
<div class="assistant-composer-context">
|
||||
<AssistantSelectionChip />
|
||||
</div>
|
||||
</template>
|
||||
<template #composer-controls>
|
||||
<AssistantContextMenu />
|
||||
<AssistantAccessPicker />
|
||||
</template>
|
||||
</ChatView>
|
||||
|
||||
<div v-else-if="assistant.sessionId" class="assistant-history">
|
||||
<template v-if="sessionLoadError">
|
||||
<p role="alert">{{ t('assistant.historyFailed') }}</p>
|
||||
<t-button variant="text" @click="validateSession(assistant.sessionId)">{{ t('common.retry') }}</t-button>
|
||||
</template>
|
||||
<t-loading v-else size="small" />
|
||||
</div>
|
||||
<div v-else class="assistant-welcome">
|
||||
<div class="assistant-welcome-body">
|
||||
<div class="assistant-welcome-icon">
|
||||
<t-icon name="compass" size="22px" />
|
||||
</div>
|
||||
<h3 class="assistant-welcome-title">{{ t('assistant.welcomeTitle') }}</h3>
|
||||
<p class="assistant-welcome-desc">{{ welcomeDescription }}</p>
|
||||
<div class="assistant-starters">
|
||||
<button v-for="starter in starters" :key="starter" type="button" class="assistant-starter"
|
||||
:disabled="starting" @click="startConversation(starter)">
|
||||
{{ starter }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="assistant-welcome-composer">
|
||||
<InputField ref="welcomeInput" :embedded-mode="true" compact :auto-focus="assistant.visible"
|
||||
:model-id="assistant.modelId" :default-model-id="defaultModelId" @update:model-id="assistant.setModel"
|
||||
@send-msg="(query) => startConversation(query)">
|
||||
<template v-if="assistant.pageSelection" #chips>
|
||||
<div class="assistant-composer-context">
|
||||
<AssistantSelectionChip />
|
||||
</div>
|
||||
</template>
|
||||
<template #controls>
|
||||
<AssistantContextMenu />
|
||||
<AssistantAccessPicker />
|
||||
</template>
|
||||
</InputField>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, provide, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'
|
||||
import ChatView from '@/views/chat/index.vue'
|
||||
import ChildAgentTabBar from '@/views/chat/components/ChildAgentTabBar.vue'
|
||||
import { createChildAgentTabs, childAgentTabsKey } from '@/composables/useChildAgentTabs'
|
||||
import InputField from '@/components/Input-field.vue'
|
||||
import PanelResizeHandle from '@/components/PanelResizeHandle.vue'
|
||||
import AssistantContextMenu from './AssistantContextMenu.vue'
|
||||
import AssistantSelectionChip from './AssistantSelectionChip.vue'
|
||||
import AssistantAccessPicker from './AssistantAccessPicker.vue'
|
||||
import { createSessions, getSessionsList, getSession, type SessionSummary } from '@/api/chat'
|
||||
import { classifyDateBucket } from '@/components/sessionGrouping'
|
||||
import { BUILTIN_WEKNORA_ASSISTANT_ID } from '@/api/agent'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useAssistantDataChange } from '@/utils/assistantDataChange'
|
||||
import {
|
||||
ASSISTANT_PANEL_MAX_WIDTH,
|
||||
ASSISTANT_PANEL_MIN_WIDTH,
|
||||
toPageContextPayload,
|
||||
toPageSelectionPayload,
|
||||
useAssistantStore,
|
||||
type AssistantOpenRequest,
|
||||
} from '@/stores/assistant'
|
||||
import { removeSession, SESSION_MUTATION_EVENT, type SessionMutationDetail } from '@/components/sessionMutations'
|
||||
import type { PageContextPayload } from '@/api/chat/streame'
|
||||
|
||||
const { t } = useI18n()
|
||||
const childTabs = createChildAgentTabs()
|
||||
provide(childAgentTabsKey, childTabs)
|
||||
const assistant = useAssistantStore()
|
||||
const auth = useAuthStore()
|
||||
useAssistantDataChange(() => { void auth.refreshFromAuthMe() }, { areas: ['workspace'] })
|
||||
const conversationOwner = computed(() => `${auth.user?.id}:${auth.effectiveTenantId}`)
|
||||
const assistantName = computed(() => assistant.displayName || t('assistant.title'))
|
||||
|
||||
// Below this the page would be too cramped beside a docked panel, so the
|
||||
// panel floats instead whatever the preference.
|
||||
const DOCK_MIN_VIEWPORT = 1100
|
||||
// The page keeps at least this much room beside a docked panel.
|
||||
const DOCK_MIN_PAGE_WIDTH = 720
|
||||
const FLOATING_MARGIN = 12
|
||||
|
||||
const viewportWidth = ref(typeof window !== 'undefined' ? window.innerWidth || 0 : 0)
|
||||
const onViewportResize = () => { viewportWidth.value = window.innerWidth }
|
||||
const canDock = computed(() => viewportWidth.value >= DOCK_MIN_VIEWPORT)
|
||||
const effectiveLayout = computed(() => assistant.layout === 'docked' && canDock.value ? 'docked' : 'floating')
|
||||
const docked = computed(() => assistant.visible && effectiveLayout.value === 'docked')
|
||||
|
||||
const panelWidth = computed(() => {
|
||||
const room = effectiveLayout.value === 'docked'
|
||||
? viewportWidth.value - DOCK_MIN_PAGE_WIDTH
|
||||
: viewportWidth.value - 2 * FLOATING_MARGIN
|
||||
return Math.max(ASSISTANT_PANEL_MIN_WIDTH, Math.min(assistant.width, room || assistant.width))
|
||||
})
|
||||
|
||||
const layoutToggleLabel = computed(() => assistant.layout === 'docked'
|
||||
? t('assistant.layout.float') : t('assistant.layout.dock'))
|
||||
const toggleLayout = () => assistant.setLayout(assistant.layout === 'docked' ? 'floating' : 'docked')
|
||||
|
||||
const resizing = ref(false)
|
||||
let resizeStartWidth = 0
|
||||
const startResize = () => {
|
||||
resizeStartWidth = panelWidth.value
|
||||
resizing.value = true
|
||||
}
|
||||
const resize = (delta: number) => assistant.setWidth(resizeStartWidth - delta)
|
||||
|
||||
// Page overlays (drawers, dialogs, side panels) stop at a docked panel's edge
|
||||
// instead of covering it: TDesign's in the unscoped styles below, ours by
|
||||
// reading --assistant-dock-width in their own styles.
|
||||
watch([docked, panelWidth], ([isDocked, width]) => {
|
||||
if (typeof document === 'undefined') return
|
||||
const root = document.documentElement
|
||||
root.classList.toggle('has-assistant-dock', isDocked)
|
||||
root.style.setProperty('--assistant-dock-width', isDocked ? `${width}px` : '0px')
|
||||
}, { immediate: true })
|
||||
|
||||
const defaultModelId = computed(() =>
|
||||
(assistant.contextAttached ? assistant.pageContext?.chatModelId : '') || '')
|
||||
|
||||
const starting = ref(false)
|
||||
// A first message belongs to the session we created, never a restored one.
|
||||
const initialMessage = ref<{
|
||||
sessionId: string
|
||||
query: string
|
||||
focus?: AssistantOpenRequest['focus']
|
||||
} | null>(null)
|
||||
const initialQuery = computed(() => initialMessage.value?.sessionId === assistant.sessionId
|
||||
? initialMessage.value.query : '')
|
||||
|
||||
const welcomeDescription = computed(() => t(assistant.contextAttached && assistant.pageContext?.agentId
|
||||
? 'assistant.agentWelcomeDesc' : 'assistant.welcomeDesc'))
|
||||
|
||||
const starters = computed(() => {
|
||||
const c = assistant.contextAttached ? assistant.pageContext : null
|
||||
if (c?.messageId) return [t('assistant.starters.messageSources'), t('assistant.starters.messageCheck')]
|
||||
if (c?.modelId) return [t('assistant.starters.modelCheck'), t('assistant.starters.modelUsage')]
|
||||
if (c?.mcpServiceId) return [t('assistant.starters.mcpTools'), t('assistant.starters.mcpCheck')]
|
||||
if (c?.page === 'settings_models') return [t('assistant.starters.modelSetup'), t('assistant.starters.modelUsage')]
|
||||
if (c?.page === 'mcp_services') return [t('assistant.starters.mcpSetup')]
|
||||
if (c?.agentId) return [
|
||||
t('assistant.starters.agentConfig'), t('assistant.starters.agentModel'), t('assistant.starters.agentKnowledge'),
|
||||
]
|
||||
if (c?.wikiSlug) return [t('assistant.starters.wikiIssues'), t('assistant.starters.wikiSummary')]
|
||||
if (c?.knowledgeId) return [t('assistant.starters.documentStatus'), t('assistant.starters.documentSummary')]
|
||||
if (c) return [t('assistant.starters.failedDocuments'), t('assistant.starters.recentActivity')]
|
||||
return [t('assistant.starters.agents'), t('assistant.starters.formats'), t('assistant.starters.createWiki')]
|
||||
})
|
||||
|
||||
// Page context is a hint, not an explicit retrieval selection. The backend
|
||||
// validates it against the agent's scope; only user selections narrow that scope.
|
||||
const hostScope = () => {
|
||||
const context = assistant.contextAttached ? assistant.pageContext : null
|
||||
const title = assistant.contextAttached ? assistant.pageTitle : ''
|
||||
const view = assistant.contextAttached ? assistant.pageView : ''
|
||||
const selection = assistant.pageSelection
|
||||
// A selection goes with one message; the next is about what is selected then.
|
||||
if (selection) assistant.setPageSelection(null)
|
||||
const focus = initialMessage.value?.sessionId === assistant.sessionId ? initialMessage.value.focus : undefined
|
||||
initialMessage.value = null
|
||||
const assistantAccess = assistant.effectiveAccessLevel
|
||||
if (!context && !title && !view && !selection) return { knowledgeBaseIds: [], pageContext: null, assistantAccess }
|
||||
const pageContext: PageContextPayload = context ? toPageContextPayload(focus ? { ...context, ...focus } : context) : {}
|
||||
if (title) pageContext.title = title
|
||||
if (view) pageContext.view = view
|
||||
if (selection) pageContext.selection = toPageSelectionPayload(selection)
|
||||
return {
|
||||
knowledgeBaseIds: [],
|
||||
pageContext,
|
||||
assistantAccess,
|
||||
}
|
||||
}
|
||||
|
||||
const welcomeInput = ref<{ focusInput?: () => void } | null>(null)
|
||||
watch(() => assistant.focusRequest, () => {
|
||||
if (!assistant.sessionId) welcomeInput.value?.focusInput?.()
|
||||
})
|
||||
|
||||
async function startConversation(query: string, focus?: AssistantOpenRequest['focus']) {
|
||||
const text = query.trim()
|
||||
if (!text || starting.value) return
|
||||
const owner = conversationOwner.value
|
||||
starting.value = true
|
||||
try {
|
||||
const res: any = await createSessions({ kind: 'assistant' })
|
||||
// A workspace switch can complete while session creation is in flight.
|
||||
if (conversationOwner.value !== owner) return
|
||||
const sessionId = res?.data?.id
|
||||
if (!sessionId) throw new Error('missing session id')
|
||||
initialMessage.value = { sessionId, query: text, focus }
|
||||
showHistory.value = false
|
||||
assistant.setSession(sessionId)
|
||||
} catch (e) {
|
||||
console.error('[Assistant] Failed to start a conversation', e)
|
||||
MessagePlugin.error(t('assistant.startFailed'))
|
||||
} finally {
|
||||
starting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => [assistant.visible, assistant.pendingRequest] as const, ([visible, request]) => {
|
||||
if (!visible || !request) return
|
||||
const { query, focus } = assistant.takePendingRequest() || {}
|
||||
assistant.restorePageContext()
|
||||
if (query) void startConversation(query, focus)
|
||||
}, { immediate: true })
|
||||
|
||||
const showHistory = ref(false)
|
||||
const selectConversationTab = (id: string) => { showHistory.value = false; childTabs.select(id) }
|
||||
const history = ref<SessionSummary[]>([])
|
||||
const historyPage = ref(0)
|
||||
const historyTotal = ref(0)
|
||||
const historyLoading = ref(false)
|
||||
const historyError = ref(false)
|
||||
const deleting = ref('')
|
||||
const readySessionId = ref('')
|
||||
const sessionLoadError = ref(false)
|
||||
let historyGeneration = 0
|
||||
|
||||
async function loadHistory(reset = false) {
|
||||
if (historyLoading.value && !reset) return
|
||||
const generation = reset ? ++historyGeneration : historyGeneration
|
||||
const owner = conversationOwner.value
|
||||
if (reset) {
|
||||
history.value = []
|
||||
historyPage.value = 0
|
||||
historyTotal.value = 0
|
||||
}
|
||||
historyLoading.value = true
|
||||
historyError.value = false
|
||||
try {
|
||||
const res: any = await getSessionsList(historyPage.value + 1, 20, undefined, 'assistant')
|
||||
if (generation !== historyGeneration || owner !== conversationOwner.value) return
|
||||
if (!res?.success) throw new Error('session list failed')
|
||||
const seen = new Set(history.value.map(session => session.id))
|
||||
history.value.push(...(res.data as SessionSummary[]).filter(session => !seen.has(session.id)))
|
||||
historyTotal.value = res.total
|
||||
historyPage.value++
|
||||
} catch {
|
||||
if (generation === historyGeneration && owner === conversationOwner.value) historyError.value = true
|
||||
} finally {
|
||||
if (generation === historyGeneration && owner === conversationOwner.value) historyLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function toggleHistory() {
|
||||
showHistory.value = !showHistory.value
|
||||
if (showHistory.value) void loadHistory(true)
|
||||
}
|
||||
|
||||
function startNewConversation() {
|
||||
showHistory.value = false
|
||||
assistant.startNewConversation()
|
||||
}
|
||||
|
||||
function selectSession(id: string) {
|
||||
assistant.setSession(id)
|
||||
showHistory.value = false
|
||||
}
|
||||
|
||||
function confirmDelete(id: string) {
|
||||
const owner = conversationOwner.value
|
||||
const dialog = DialogPlugin.confirm({
|
||||
header: t('chatHeader.deleteConfirmTitle'),
|
||||
body: t('chatHeader.deleteConfirmBody'),
|
||||
confirmBtn: { content: t('common.delete'), theme: 'danger' },
|
||||
cancelBtn: t('common.cancel'),
|
||||
theme: 'warning',
|
||||
onConfirm: async () => {
|
||||
if (deleting.value || owner !== conversationOwner.value) return
|
||||
deleting.value = id
|
||||
try {
|
||||
await removeSession(id)
|
||||
if (owner !== conversationOwner.value) return
|
||||
if (id === assistant.sessionId) startNewConversation()
|
||||
if (showHistory.value) await loadHistory(true)
|
||||
dialog.destroy()
|
||||
} catch {
|
||||
if (owner === conversationOwner.value) MessagePlugin.error(t('chat.deleteSessionFailed'))
|
||||
} finally {
|
||||
deleting.value = ''
|
||||
}
|
||||
},
|
||||
onClose: () => dialog.destroy(),
|
||||
})
|
||||
}
|
||||
|
||||
async function validateSession(id: string) {
|
||||
const owner = conversationOwner.value
|
||||
readySessionId.value = ''
|
||||
sessionLoadError.value = false
|
||||
if (!id) return
|
||||
if (id === initialMessage.value?.sessionId) {
|
||||
readySessionId.value = id
|
||||
return
|
||||
}
|
||||
try {
|
||||
const res: any = await getSession(id)
|
||||
if (owner !== conversationOwner.value || id !== assistant.sessionId) return
|
||||
if (res?.data?.kind !== 'assistant') {
|
||||
startNewConversation()
|
||||
return
|
||||
}
|
||||
readySessionId.value = id
|
||||
} catch (error: any) {
|
||||
if (owner !== conversationOwner.value || id !== assistant.sessionId) return
|
||||
const status = error?.$httpStatus ?? error?.response?.status ?? error?.status
|
||||
if (status === 403 || status === 404) startNewConversation()
|
||||
else sessionLoadError.value = true
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => assistant.sessionId, (id) => {
|
||||
childTabs.reset()
|
||||
if (id !== initialMessage.value?.sessionId) initialMessage.value = null
|
||||
void validateSession(id)
|
||||
}, { immediate: true })
|
||||
|
||||
watch(conversationOwner, () => {
|
||||
childTabs.reset()
|
||||
++historyGeneration
|
||||
history.value = []
|
||||
historyTotal.value = 0
|
||||
historyPage.value = 0
|
||||
historyLoading.value = false
|
||||
historyError.value = false
|
||||
showHistory.value = false
|
||||
})
|
||||
|
||||
const handleSessionMutation = (event: Event) => {
|
||||
const detail = (event as CustomEvent<SessionMutationDetail>).detail
|
||||
if (detail?.removed && detail.sessionId === assistant.sessionId) startNewConversation()
|
||||
}
|
||||
onMounted(() => {
|
||||
window.addEventListener(SESSION_MUTATION_EVENT, handleSessionMutation)
|
||||
window.addEventListener('resize', onViewportResize)
|
||||
})
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener(SESSION_MUTATION_EVENT, handleSessionMutation)
|
||||
window.removeEventListener('resize', onViewportResize)
|
||||
if (typeof document !== 'undefined') {
|
||||
document.documentElement.classList.remove('has-assistant-dock')
|
||||
document.documentElement.style.removeProperty('--assistant-dock-width')
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.assistant-panel {
|
||||
display: none;
|
||||
position: relative;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
box-sizing: border-box;
|
||||
background: var(--td-bg-color-container);
|
||||
|
||||
&.is-open {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
// A column of the platform layout: the page to its left narrows.
|
||||
&.is-docked {
|
||||
flex-shrink: 0;
|
||||
height: 100%;
|
||||
border-left: 1px solid var(--td-component-stroke);
|
||||
}
|
||||
|
||||
// Above page drawers (1500), below dialogs and the settings shell; no mask.
|
||||
&.is-floating {
|
||||
position: fixed;
|
||||
top: 12px;
|
||||
right: 12px;
|
||||
bottom: 12px;
|
||||
z-index: 1600;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-lg);
|
||||
box-shadow: var(--td-shadow-3);
|
||||
overflow: hidden;
|
||||
|
||||
&.is-open {
|
||||
animation: assistant-panel-in var(--app-motion-base) cubic-bezier(0.22, 0.61, 0.36, 1);
|
||||
}
|
||||
}
|
||||
|
||||
&.is-resizing {
|
||||
user-select: none;
|
||||
|
||||
.assistant-panel__body {
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes assistant-panel-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateX(16px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
.assistant-composer-context {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
height: 28px;
|
||||
flex: 0 0 100%;
|
||||
|
||||
:deep(.assistant-selection-chip) {
|
||||
flex: 0 1 auto;
|
||||
max-width: 100%;
|
||||
height: 26px;
|
||||
}
|
||||
}
|
||||
|
||||
.assistant-panel__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
flex: 0 0 var(--app-chat-header-height);
|
||||
min-width: 0;
|
||||
padding: 0 12px 0 16px;
|
||||
box-sizing: border-box;
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
}
|
||||
|
||||
.assistant-panel__header-icon {
|
||||
flex-shrink: 0;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
margin-right: 4px;
|
||||
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);
|
||||
}
|
||||
|
||||
.assistant-panel__title {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
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;
|
||||
}
|
||||
|
||||
.assistant-panel__action {
|
||||
flex-shrink: 0;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-md);
|
||||
background: transparent;
|
||||
color: var(--td-text-color-secondary);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
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 {
|
||||
cursor: not-allowed;
|
||||
color: var(--td-text-color-disabled);
|
||||
}
|
||||
|
||||
&[aria-pressed='true'] {
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.assistant-panel__body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.assistant-panel__conversation {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
|
||||
// Align the assistant composer with the main conversation composer.
|
||||
:deep(.input-container.is-embedded) {
|
||||
padding-bottom: max(8px, env(safe-area-inset-bottom));
|
||||
}
|
||||
}
|
||||
|
||||
.assistant-history {
|
||||
overflow-y: auto;
|
||||
padding: 12px;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-sm);
|
||||
}
|
||||
|
||||
.assistant-history__row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
border-radius: var(--app-radius-md);
|
||||
|
||||
&:hover, &.is-current {
|
||||
background: var(--td-bg-color-container-hover);
|
||||
}
|
||||
|
||||
&.is-current {
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
}
|
||||
|
||||
.assistant-history__select {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 10px 8px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
|
||||
span, small {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
small {
|
||||
margin-top: 4px;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
}
|
||||
|
||||
.assistant-welcome {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.assistant-welcome-body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 0 24px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.assistant-welcome-icon {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: var(--app-radius-md, 8px);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
.assistant-welcome-title {
|
||||
margin: 4px 0 0;
|
||||
font-size: var(--app-text-lg);
|
||||
font-weight: 600;
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.assistant-welcome-desc {
|
||||
margin: 0;
|
||||
max-width: 420px;
|
||||
font-size: var(--app-text-md);
|
||||
line-height: 1.6;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.assistant-starters {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.assistant-starter {
|
||||
padding: 6px 12px;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--td-radius-medium);
|
||||
background: var(--td-bg-color-container);
|
||||
color: var(--td-text-color-primary);
|
||||
font-family: inherit;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 18px;
|
||||
cursor: pointer;
|
||||
transition: background var(--app-motion-fast), border-color var(--app-motion-fast);
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: var(--td-bg-color-container-hover);
|
||||
border-color: var(--td-component-border);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
cursor: not-allowed;
|
||||
color: var(--td-text-color-disabled);
|
||||
}
|
||||
}
|
||||
|
||||
// Same inset as the composer inside a conversation.
|
||||
.assistant-welcome-composer {
|
||||
flex-shrink: 0;
|
||||
padding: 12px 16px max(8px, env(safe-area-inset-bottom));
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="less">
|
||||
html.has-assistant-dock {
|
||||
.t-drawer:not(.t-drawer--attach):not(.chat-artifacts-drawer),
|
||||
.t-dialog__ctx--fixed .t-dialog__mask,
|
||||
.t-dialog__ctx--fixed .t-dialog__wrap {
|
||||
width: calc(100% - var(--assistant-dock-width));
|
||||
}
|
||||
|
||||
.t-drawer--right:not(.t-drawer--attach):not(.chat-artifacts-drawer) {
|
||||
right: var(--assistant-dock-width);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,159 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div v-if="position" ref="bubble" class="assistant-selection-bubble" data-assistant-ignore role="toolbar"
|
||||
:aria-label="t('assistant.bubble.label')" :style="{ left: `${position.left}px`, top: `${position.top}px` }"
|
||||
@mousedown.prevent>
|
||||
<button type="button" class="assistant-selection-bubble__btn is-primary" @click="run('ask')">
|
||||
<t-icon name="compass" />{{ t('assistant.bubble.ask') }}
|
||||
</button>
|
||||
<span class="assistant-selection-bubble__divider" aria-hidden="true" />
|
||||
<button v-for="action in QUICK_ACTIONS" :key="action" type="button" class="assistant-selection-bubble__btn"
|
||||
@click="run(action)">
|
||||
{{ t(`assistant.bubble.${action}`) }}
|
||||
</button>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useAssistantStore } from '@/stores/assistant'
|
||||
import { selectedTextControl } from '@/utils/pageAwareness'
|
||||
|
||||
const QUICK_ACTIONS = ['polish', 'rewrite', 'translate', 'continue'] as const
|
||||
type Action = 'ask' | typeof QUICK_ACTIONS[number]
|
||||
|
||||
const { t } = useI18n()
|
||||
const assistant = useAssistantStore()
|
||||
const bubble = ref<HTMLElement | null>(null)
|
||||
const position = ref<{ left: number; top: number } | null>(null)
|
||||
|
||||
// Where the pointer let go of the selection, to put the bar beside it.
|
||||
let lastPointer = { x: 0, y: 0, at: 0 }
|
||||
const MARGIN = 8
|
||||
|
||||
const hide = () => { position.value = null }
|
||||
|
||||
async function place() {
|
||||
const control = selectedTextControl()
|
||||
if (!control) return hide()
|
||||
let x: number
|
||||
let y: number
|
||||
if (Date.now() - lastPointer.at < 1500) {
|
||||
({ x, y } = lastPointer)
|
||||
} else {
|
||||
const box = control.getBoundingClientRect()
|
||||
x = box.right - 120
|
||||
y = box.top + 12
|
||||
}
|
||||
position.value = { left: x, top: y - 44 }
|
||||
await nextTick()
|
||||
const width = bubble.value?.offsetWidth || 320
|
||||
const height = bubble.value?.offsetHeight || 34
|
||||
const top = y - height - 10 < MARGIN ? y + 16 : y - height - 10
|
||||
const left = Math.min(Math.max(MARGIN, x - width / 2), window.innerWidth - width - MARGIN)
|
||||
position.value = { left, top }
|
||||
}
|
||||
|
||||
// Only a selection in a field the assistant can write to gets the bar.
|
||||
watch(() => assistant.pageSelection, selection => {
|
||||
if (!selection?.ref || !assistant.pageAccess) hide()
|
||||
else void place()
|
||||
})
|
||||
|
||||
function run(action: Action) {
|
||||
hide()
|
||||
if (action === 'ask') assistant.focusComposer()
|
||||
else assistant.ask(t(`assistant.bubble.prompts.${action}`))
|
||||
}
|
||||
|
||||
const inside = (event: Event) => !!bubble.value && event.target instanceof Node && bubble.value.contains(event.target)
|
||||
const onPointerUp = (event: PointerEvent) => {
|
||||
if (!inside(event)) lastPointer = { x: event.clientX, y: event.clientY, at: Date.now() }
|
||||
}
|
||||
const onPointerDown = (event: PointerEvent) => {
|
||||
if (!inside(event)) hide()
|
||||
}
|
||||
// Extending the selection from the keyboard keeps the bar; typing does not.
|
||||
const KEEP_KEYS = new Set(['Shift', 'Meta', 'Control', 'Alt', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End'])
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape' || !KEEP_KEYS.has(event.key)) hide()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('pointerup', onPointerUp, true)
|
||||
document.addEventListener('pointerdown', onPointerDown, true)
|
||||
document.addEventListener('keydown', onKeyDown, true)
|
||||
document.addEventListener('scroll', hide, true)
|
||||
window.addEventListener('resize', hide)
|
||||
})
|
||||
onUnmounted(() => {
|
||||
document.removeEventListener('pointerup', onPointerUp, true)
|
||||
document.removeEventListener('pointerdown', onPointerDown, true)
|
||||
document.removeEventListener('keydown', onKeyDown, true)
|
||||
document.removeEventListener('scroll', hide, true)
|
||||
window.removeEventListener('resize', hide)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.assistant-selection-bubble {
|
||||
position: fixed;
|
||||
z-index: 5000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
padding: 3px;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--td-radius-large);
|
||||
background: var(--td-bg-color-container);
|
||||
box-shadow: var(--td-shadow-2);
|
||||
animation: assistant-selection-bubble-in var(--app-motion-fast, 120ms) ease-out;
|
||||
}
|
||||
|
||||
@keyframes assistant-selection-bubble-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(4px);
|
||||
}
|
||||
}
|
||||
|
||||
.assistant-selection-bubble__btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
height: 28px;
|
||||
padding: 0 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);
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
background: var(--td-bg-color-container-hover);
|
||||
}
|
||||
|
||||
&.is-primary {
|
||||
color: var(--td-brand-color);
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
|
||||
.assistant-selection-bubble__divider {
|
||||
width: 1px;
|
||||
height: 16px;
|
||||
margin: 0 2px;
|
||||
background: var(--td-component-stroke);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.assistant-selection-bubble {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,114 @@
|
||||
<template>
|
||||
<t-tooltip v-if="selection" placement="top" :content="tooltip" :overlay-inner-style="{ maxWidth: '360px' }">
|
||||
<span class="assistant-selection-chip">
|
||||
<t-icon name="cursor" class="assistant-selection-chip__icon" />
|
||||
<span class="assistant-selection-chip__label">{{ label }}</span>
|
||||
<span class="assistant-selection-chip__text">{{ excerpt }}</span>
|
||||
<span class="assistant-selection-chip__remove" role="button" :aria-label="t('assistant.selection.detach')"
|
||||
@click.stop="assistant.setPageSelection(null)">×</span>
|
||||
</span>
|
||||
</t-tooltip>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useAssistantStore } from '@/stores/assistant'
|
||||
|
||||
const { t } = useI18n()
|
||||
const assistant = useAssistantStore()
|
||||
const selection = computed(() => assistant.pageSelection)
|
||||
|
||||
const flat = (text: string) => text.replace(/\s+/g, ' ').trim()
|
||||
|
||||
const label = computed(() => {
|
||||
const s = selection.value
|
||||
if (!s) return ''
|
||||
if (s.startLine && s.endLine && s.endLine > s.startLine) {
|
||||
return t('assistant.selection.lines', { count: s.endLine - s.startLine + 1 })
|
||||
}
|
||||
return t('assistant.selection.label')
|
||||
})
|
||||
|
||||
const excerpt = computed(() => {
|
||||
const text = flat(selection.value?.text || '')
|
||||
return text.length > 24 ? `${text.slice(0, 23)}…` : text
|
||||
})
|
||||
|
||||
const tooltip = computed(() => {
|
||||
const s = selection.value
|
||||
if (!s) return ''
|
||||
const text = flat(s.text)
|
||||
const body = text.length > 300 ? `${text.slice(0, 299)}…` : text
|
||||
return s.field ? t('assistant.selection.tipField', { field: s.field, text: body }) : t('assistant.selection.tip', { text: body })
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
@import '@/components/css/chat-resource-chips.less';
|
||||
|
||||
.assistant-selection-chip {
|
||||
.chat-resource-chip-surface();
|
||||
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
min-height: 26px;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
padding: 3px 6px;
|
||||
border-radius: var(--td-radius-medium);
|
||||
box-sizing: border-box;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 18px;
|
||||
|
||||
&:hover {
|
||||
.chat-resource-chip-hover();
|
||||
}
|
||||
}
|
||||
|
||||
.assistant-selection-chip__icon {
|
||||
flex-shrink: 0;
|
||||
font-size: var(--app-text-base);
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
.assistant-selection-chip__label {
|
||||
flex-shrink: 0;
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.assistant-selection-chip__text {
|
||||
min-width: 0;
|
||||
max-width: 200px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.assistant-selection-chip__remove {
|
||||
display: inline-flex;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border-radius: 50%;
|
||||
font-size: var(--app-text-base);
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
opacity: 0.5;
|
||||
transition: opacity var(--app-motion-fast), background var(--app-motion-fast);
|
||||
|
||||
.assistant-selection-chip:hover & {
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
opacity: 1;
|
||||
background: var(--td-bg-color-component);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,162 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div v-if="notice && undoable && box" class="page-fill-notice" data-assistant-ignore role="status"
|
||||
:style="{ left: `${box.left}px`, top: `${box.top}px` }" @mouseenter="pause" @mouseleave="resume">
|
||||
<t-icon name="ai-edit" class="page-fill-notice__icon" />
|
||||
<span class="page-fill-notice__text">{{ t('assistant.fillNotice.title', { count: notice.count }) }}</span>
|
||||
<button type="button" class="page-fill-notice__btn" :disabled="undoing" @click="undo">
|
||||
{{ t('assistant.fillNotice.undo') }}
|
||||
</button>
|
||||
<button type="button" class="page-fill-notice__close" :aria-label="t('assistant.fillNotice.dismiss')"
|
||||
@click="dismiss">
|
||||
<t-icon name="close" />
|
||||
</button>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onUnmounted, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { canUndoFill, lastPageFill, undoFill, type PageFillNotice } from '@/utils/pageFill'
|
||||
|
||||
const SHOW_MS = 10_000
|
||||
const WIDTH_GUESS = 240
|
||||
|
||||
const { t } = useI18n()
|
||||
const notice = ref<PageFillNotice | null>(null)
|
||||
const box = ref<{ left: number; top: number } | null>(null)
|
||||
const undoing = ref(false)
|
||||
const undoable = computed(() => !!notice.value && canUndoFill(notice.value.key))
|
||||
|
||||
let timer = 0
|
||||
let frame = 0
|
||||
|
||||
// Sits on the top edge of the field it changed, following it as the page scrolls.
|
||||
function track() {
|
||||
const anchor = notice.value?.anchor.deref()
|
||||
if (!anchor?.isConnected) return dismiss()
|
||||
const rect = anchor.getBoundingClientRect()
|
||||
const onScreen = rect.bottom > 0 && rect.top < window.innerHeight && rect.width > 0
|
||||
if (!onScreen) {
|
||||
box.value = null
|
||||
} else {
|
||||
const top = rect.top - 36 >= 4 ? rect.top - 36 : rect.top + 6
|
||||
const left = Math.max(8, Math.min(rect.right - WIDTH_GUESS, window.innerWidth - WIDTH_GUESS - 8))
|
||||
box.value = { left, top }
|
||||
}
|
||||
frame = requestAnimationFrame(track)
|
||||
}
|
||||
|
||||
function resume() {
|
||||
window.clearTimeout(timer)
|
||||
timer = window.setTimeout(dismiss, SHOW_MS)
|
||||
}
|
||||
function pause() {
|
||||
window.clearTimeout(timer)
|
||||
}
|
||||
function dismiss() {
|
||||
window.clearTimeout(timer)
|
||||
cancelAnimationFrame(frame)
|
||||
notice.value = null
|
||||
box.value = null
|
||||
}
|
||||
|
||||
watch(lastPageFill, next => {
|
||||
dismiss()
|
||||
if (!next) return
|
||||
notice.value = next
|
||||
track()
|
||||
resume()
|
||||
})
|
||||
|
||||
// Undone from the chat card: nothing left to offer here.
|
||||
watch(undoable, can => {
|
||||
if (!can && notice.value) dismiss()
|
||||
})
|
||||
|
||||
async function undo() {
|
||||
const current = notice.value
|
||||
if (!current) return
|
||||
undoing.value = true
|
||||
try {
|
||||
const { skipped } = await undoFill(current.key)
|
||||
if (skipped > 0) MessagePlugin.warning(t('agentStream.pageEdit.undoSkipped', { count: skipped }))
|
||||
} finally {
|
||||
undoing.value = false
|
||||
dismiss()
|
||||
}
|
||||
}
|
||||
|
||||
onUnmounted(dismiss)
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.page-fill-notice {
|
||||
position: fixed;
|
||||
z-index: 5000;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: 30px;
|
||||
padding: 0 4px 0 10px;
|
||||
border: 1px solid var(--td-brand-color-focus);
|
||||
border-radius: var(--td-radius-large);
|
||||
background: var(--td-bg-color-container);
|
||||
box-shadow: var(--td-shadow-2);
|
||||
font-size: var(--app-text-sm);
|
||||
white-space: nowrap;
|
||||
animation: page-fill-notice-in var(--app-motion-fast, 120ms) ease-out;
|
||||
}
|
||||
|
||||
@keyframes page-fill-notice-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(4px);
|
||||
}
|
||||
}
|
||||
|
||||
.page-fill-notice__icon {
|
||||
color: var(--td-brand-color);
|
||||
font-size: var(--app-text-base);
|
||||
}
|
||||
|
||||
.page-fill-notice__text {
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.page-fill-notice__btn,
|
||||
.page-fill-notice__close {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 24px;
|
||||
border: 0;
|
||||
border-radius: var(--td-radius-medium);
|
||||
background: transparent;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: var(--td-bg-color-container-hover);
|
||||
}
|
||||
}
|
||||
|
||||
.page-fill-notice__btn {
|
||||
padding: 0 8px;
|
||||
color: var(--td-brand-color);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.page-fill-notice__close {
|
||||
width: 24px;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.page-fill-notice {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
Reference in new issue
Block a user