Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(assistant): add contextual entry points and guided actions (#4757)

lyingbug18e22de6b239
diff --git a/frontend/src/assets/img/assistant.svg b/frontend/src/assets/img/assistant.svg
new file mode 100644
index 000000000..f1211550b
--- /dev/null
+++ b/frontend/src/assets/img/assistant.svg
@@ -0,0 +1,4 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
+ <path d="M9.5 4.5c.8 5.7 2.3 7.2 8 8-5.7.8-7.2 2.3-8 8-.8-5.7-2.3-7.2-8-8 5.7-.8 7.2-2.3 8-8Z"/>
+ <path d="M18.5 1.5c.4 2.8 1.2 3.6 4 4-2.8.4-3.6 1.2-4 4-.4-2.8-1.2-3.6-4-4 2.8-.4 3.6-1.2 4-4Z"/>
+</svg>
diff --git a/frontend/src/components/ChatActionIcon.vue b/frontend/src/components/ChatActionIcon.vue
index e726fe08b..edfe57e8a 100644
--- a/frontend/src/components/ChatActionIcon.vue
+++ b/frontend/src/components/ChatActionIcon.vue
@@ -19,10 +19,6 @@
<path d="M19 21l-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16Z" />
<path d="M9 9h6m-3-3v6" />
</template>
- <template v-else-if="name === 'compass'">
- <circle cx="12" cy="12" r="9" />
- <path d="m16 8-2.5 5.5L8 16l2.5-5.5L16 8Z" />
- </template>
<template v-else-if="name === 'folder'">
<path d="M3 7V6a2 2 0 0 1 2-2h4l2 3h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z" />
</template>
@@ -53,6 +49,6 @@
<script setup lang="ts">
defineProps<{
- name: 'copy' | 'git-branch' | 'rollback' | 'bookmark-add' | 'compass' | 'folder' | 'info-circle' | 'play' | 'resume' | 'pause' | 'edit' | 'delete'
+ name: 'copy' | 'git-branch' | 'rollback' | 'bookmark-add' | 'folder' | 'info-circle' | 'play' | 'resume' | 'pause' | 'edit' | 'delete'
}>()
</script>
diff --git a/frontend/src/components/GlobalCommandPalette/ResultItem.vue b/frontend/src/components/GlobalCommandPalette/ResultItem.vue
index 58669ecda..a4cc0255e 100644
--- a/frontend/src/components/GlobalCommandPalette/ResultItem.vue
+++ b/frontend/src/components/GlobalCommandPalette/ResultItem.vue
@@ -8,7 +8,8 @@
>
<div class="cmdk-item__icon">
<slot name="icon">
- <t-icon :name="iconName" size="14px" />
+ <ResourceIcon v-if="iconName === 'assistant'" type="assistant" :size="14" />
+ <t-icon v-else :name="iconName" size="14px" />
</slot>
</div>
<div class="cmdk-item__body">
@@ -37,6 +38,8 @@
</template>
<script setup lang="ts">
+import ResourceIcon from '@/components/icons/ResourceIcon.vue'
+
/**
* A single result row inside the command palette.
* Host component owns selection state; this one just mirrors it via the
diff --git a/frontend/src/components/GlobalCommandPalette/commands.ts b/frontend/src/components/GlobalCommandPalette/commands.ts
index 5509b369a..9ed99412f 100644
--- a/frontend/src/components/GlobalCommandPalette/commands.ts
+++ b/frontend/src/components/GlobalCommandPalette/commands.ts
@@ -12,7 +12,7 @@ export interface CmdkCommand {
id: string
/** Localized display label. */
label: string
- /** TDesign icon name rendered on the left. */
+ /** TDesign icon name, or "assistant" for the shared assistant icon. */
icon: string
/** Extra tokens used purely for fuzzy matching (aliases, synonyms). */
keywords?: string[]
@@ -41,7 +41,7 @@ export function buildCommands(ctx: CommandContext): CmdkCommand[] {
{
id: 'open-assistant',
label: t('commandPalette.quick.assistant', { name: assistantName(t) }),
- icon: 'compass',
+ icon: 'assistant',
keywords: ['assistant', 'help', 'weknora', 'kora', '助手', '帮助', 'ассистент', useAssistantStore().displayName].filter(Boolean),
run: () => {
close()
diff --git a/frontend/src/components/ModelEditorDialog.vue b/frontend/src/components/ModelEditorDialog.vue
index a7a8cf630..124014aa8 100644
--- a/frontend/src/components/ModelEditorDialog.vue
+++ b/frontend/src/components/ModelEditorDialog.vue
@@ -1,5 +1,6 @@
<template>
<SettingDrawer :visible="dialogVisible" :title="isEdit ? $t('model.editor.editTitle') : $t('model.editor.addTitle')"
+ :z-index="2300"
:description="getModalDescription()" :icon="modelTypeIcon" :confirm-loading="saving" :cancel-disabled="saving"
:confirm-text="$t('model.editor.saveAndClose')"
:close-on-overlay-click="!saving" :close-on-esc-keydown="!saving"
@@ -33,9 +34,14 @@
<div v-if="remoteChecked && !remoteAvailable" class="connection-result error">
<div class="connection-result__header">
<strong>{{ $t('model.editor.connectionFailed') }}</strong>
- <t-button size="small" variant="text" @click="copyWithToast(remoteMessage, 'common.copied')">
- {{ $t('common.copy') }}
- </t-button>
+ <div class="connection-result__actions">
+ <AssistantActionButton :label="$t('assistant.actions.diagnose')"
+ :query="$t('assistant.prompts.modelFailure')" :disabled="remoteStale || checking || saving"
+ :selection="{ field: $t('model.editor.connectionFailed'), text: remoteMessage }" />
+ <t-button size="small" variant="text" @click="copyWithToast(remoteMessage, 'common.copied')">
+ {{ $t('common.copy') }}
+ </t-button>
+ </div>
</div>
<div class="connection-result__details" tabindex="0">{{ remoteMessage }}</div>
</div>
@@ -644,6 +650,7 @@ import { levelLabelKey, supportedLevels } from '@/utils/reasoningEffort'
import { DEFAULT_MODEL_CONTEXT_WINDOW, formatTokenCount } from '@/utils/contextWindow'
import { copyWithToast } from '@/utils/clipboard'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
+import AssistantActionButton from '@/components/assistant/AssistantActionButton.vue'
import CredentialResource, {
type CredentialFieldDef,
type CredentialResourceApi,
@@ -2474,6 +2481,12 @@ const handleCancel = () => {
line-height: 1.5;
user-select: text;
}
+
+ &__actions {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ }
}
// Status icon variant used inside the footer button.
diff --git a/frontend/src/components/assistant/AssistantActionButton.test.ts b/frontend/src/components/assistant/AssistantActionButton.test.ts
new file mode 100644
index 000000000..9041ddd70
--- /dev/null
+++ b/frontend/src/components/assistant/AssistantActionButton.test.ts
@@ -0,0 +1,62 @@
+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 { descriptor } = parse(readFileSync(new URL('./AssistantActionButton.vue', import.meta.url), 'utf8'))
+const script = compileScript(descriptor, { id: 'assistant-action-test', inlineTemplate: true }).content
+
+function fixture(selection?: { text: string; field?: string }) {
+ const calls: Array<[string, unknown?]> = []
+ const assistant = {
+ pageAccess: true,
+ displayName: 'Assistant',
+ setPageSelection: (value: unknown) => calls.push(['selection', value]),
+ restorePageContext: () => calls.push(['context']),
+ ask: (query: string) => calls.push(['ask', query]),
+ }
+ const dependencies: Record<string, unknown> = {
+ vue,
+ 'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
+ '@/stores/assistant': { useAssistantStore: () => assistant },
+ './AssistantButton.vue': { render: () => null },
+ }
+ const exports: any = {}
+ runInNewContext(ts.transpileModule(script, {
+ compilerOptions: { module: ts.ModuleKind.CommonJS },
+ }).outputText, { exports, require: (name: string) => dependencies[name] })
+ const props = { label: 'Improve prompt', query: 'Improve the attached prompt', selection, disabled: false }
+ const render = exports.default.setup(props, { expose() {} })
+ return { assistant, calls, props, render, click: () => render({}, []).props.onClick({ stopPropagation() {} }) }
+}
+
+test('contextual actions attach a snapshot before asking in the current conversation', () => {
+ const selection = { text: 'Current prompt', field: 'System prompt' }
+ const f = fixture(selection)
+ f.click()
+ assert.deepEqual(f.calls.map(([name]) => name), ['selection', 'context', 'ask'])
+ assert.deepEqual({ ...f.calls[0][1] as object }, selection)
+ assert.equal(f.calls[2][1], f.props.query)
+ selection.text = 'Later edit'
+ assert.equal((f.calls[0][1] as { text: string }).text, 'Current prompt')
+})
+
+test('an empty prompt clears any previous selection', () => {
+ for (const selection of [undefined, { text: ' \n ' }]) {
+ const f = fixture(selection)
+ f.click()
+ assert.equal(f.calls[0][1], null)
+ }
+})
+
+test('actions respect page access and expose their disabled state', () => {
+ const f = fixture()
+ f.props.disabled = true
+ assert.equal(f.render({}, []).props.disabled, true)
+ f.assistant.pageAccess = false
+ assert.equal(f.render({}, []).type, vue.Comment)
+ assert.equal(f.calls.length, 0)
+})
diff --git a/frontend/src/components/assistant/AssistantActionButton.vue b/frontend/src/components/assistant/AssistantActionButton.vue
new file mode 100644
index 000000000..6f5c4137f
--- /dev/null
+++ b/frontend/src/components/assistant/AssistantActionButton.vue
@@ -0,0 +1,26 @@
+<template>
+ <AssistantButton v-if="assistant.pageAccess" :label="label" :disabled="disabled" :icon-only="iconOnly"
+ :title="iconOnly ? label : assistant.displayName || t('assistant.title')" @click.stop="askAssistant" />
+</template>
+
+<script setup lang="ts">
+import { useI18n } from 'vue-i18n'
+import { useAssistantStore, type AssistantPageSelection } from '@/stores/assistant'
+import AssistantButton from './AssistantButton.vue'
+
+const { t } = useI18n()
+const assistant = useAssistantStore()
+const props = defineProps<{
+ label: string
+ query: string
+ iconOnly?: boolean
+ selection?: AssistantPageSelection
+ disabled?: boolean
+}>()
+
+function askAssistant() {
+ assistant.setPageSelection(props.selection?.text.trim() ? { ...props.selection } : null)
+ assistant.restorePageContext()
+ assistant.ask(props.query)
+}
+</script>
diff --git a/frontend/src/components/assistant/AssistantActionsButton.vue b/frontend/src/components/assistant/AssistantActionsButton.vue
new file mode 100644
index 000000000..453d756d8
--- /dev/null
+++ b/frontend/src/components/assistant/AssistantActionsButton.vue
@@ -0,0 +1,31 @@
+<template>
+ <AssistantButton v-if="assistant.pageAccess" :label="label" :icon-only="iconOnly" :disabled="disabled"
+ @click.stop="openAssistant" />
+</template>
+
+<script setup lang="ts">
+import { nextTick } from 'vue'
+import { useAssistantStore, type AssistantContextAction, type AssistantPageSelection } from '@/stores/assistant'
+import AssistantButton from './AssistantButton.vue'
+
+const props = defineProps<{
+ label: string
+ iconOnly?: boolean
+ disabled?: boolean
+ selection?: AssistantPageSelection
+ actions: AssistantContextAction[]
+}>()
+const emit = defineEmits<{ beforeOpen: [] }>()
+const assistant = useAssistantStore()
+
+async function openAssistant() {
+ if (props.disabled || !assistant.pageAccess) return
+ const suggestions = { label: props.label, actions: props.actions.map(action => ({ ...action })) }
+ assistant.setPageSelection(props.selection?.text.trim() ? { ...props.selection } : null)
+ emit('beforeOpen')
+ // Let the owning page publish the selected message/resource before opening.
+ await nextTick()
+ assistant.restorePageContext()
+ assistant.showActionSuggestions(suggestions)
+}
+</script>
diff --git a/frontend/src/components/assistant/AssistantButton.vue b/frontend/src/components/assistant/AssistantButton.vue
new file mode 100644
index 000000000..a8b18058d
--- /dev/null
+++ b/frontend/src/components/assistant/AssistantButton.vue
@@ -0,0 +1,69 @@
+<template>
+ <button type="button" class="assistant-button" :class="{ 'is-icon-only': iconOnly, 'is-active': active }"
+ :disabled="disabled" :aria-label="label" :title="iconOnly ? label : undefined" data-assistant-ignore>
+ <ResourceIcon type="assistant" :size="iconSize ?? (iconOnly ? 16 : 14)" />
+ <span v-if="!iconOnly" class="assistant-button__label">{{ label }}</span>
+ </button>
+</template>
+
+<script setup lang="ts">
+import ResourceIcon from '@/components/icons/ResourceIcon.vue'
+
+defineProps<{
+ label: string
+ iconOnly?: boolean
+ iconSize?: number
+ active?: boolean
+ disabled?: boolean
+}>()
+</script>
+
+<style lang="less" scoped>
+.assistant-button {
+ --wails-draggable: no-drag;
+ display: inline-flex;
+ flex-shrink: 0;
+ align-items: center;
+ justify-content: center;
+ gap: 4px;
+ box-sizing: border-box;
+ height: 26px;
+ padding: 0 6px;
+ border: none;
+ border-radius: var(--app-radius-sm);
+ background: transparent;
+ color: var(--td-text-color-secondary);
+ font: inherit;
+ font-size: var(--app-text-sm);
+ white-space: nowrap;
+ cursor: pointer;
+ transition: background var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
+
+ &.is-icon-only {
+ width: 28px;
+ height: 28px;
+ padding: 0;
+ }
+
+ &.is-active,
+ &:hover:not(:disabled) {
+ background: var(--td-bg-color-container-hover);
+ color: var(--td-brand-color);
+ }
+
+ &:active:not(:disabled) {
+ background: var(--td-bg-color-container-active);
+ color: var(--td-brand-color);
+ }
+
+ &:disabled {
+ color: var(--td-text-color-disabled);
+ cursor: not-allowed;
+ }
+
+ &:focus-visible {
+ outline: 2px solid var(--td-brand-color);
+ outline-offset: 2px;
+ }
+}
+</style>
diff --git a/frontend/src/components/assistant/AssistantCreateDialog.vue b/frontend/src/components/assistant/AssistantCreateDialog.vue
new file mode 100644
index 000000000..a3a478943
--- /dev/null
+++ b/frontend/src/components/assistant/AssistantCreateDialog.vue
@@ -0,0 +1,186 @@
+<template>
+ <t-dialog v-model:visible="visible" width="520px" placement="center"
+ dialog-class-name="assistant-create-dialog" :z-index="2300" :close-on-overlay-click="false" :close-btn="false">
+ <template #header>
+ <div class="assistant-create__heading">
+ <ResourceIcon type="assistant" :size="18" class="assistant-create__icon" aria-hidden="true" />
+ <span>{{ t(`assistant.create.${kind}Title`) }}</span>
+ <button type="button" class="assistant-create__close" :aria-label="t('common.close')" @click="visible = false">
+ <svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
+ <path d="M15 5L5 15M5 5L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
+ </svg>
+ </button>
+ </div>
+ </template>
+ <div class="assistant-create">
+ <p class="assistant-create__hint">{{ t(`assistant.create.${kind}Hint`) }}</p>
+ <label class="assistant-create__field">
+ <span class="assistant-create__label">{{ t('assistant.create.requestLabel') }}</span>
+ <t-textarea v-model="description"
+ :placeholder="t(`assistant.create.${kind}Placeholder`)" :autosize="{ minRows: 4, maxRows: 8 }"
+ :maxlength="2000" autofocus />
+ </label>
+ </div>
+ <template #footer>
+ <div class="assistant-create__actions">
+ <t-button variant="outline" theme="default" @click="manual">{{ t('assistant.create.manual') }}</t-button>
+ <t-button theme="primary" :disabled="!description.trim()" :loading="submitting" @click="create">
+ <template #icon><ResourceIcon type="assistant" :size="16" /></template>
+ {{ t('assistant.create.start') }}
+ </t-button>
+ </div>
+ </template>
+ </t-dialog>
+</template>
+
+<script setup lang="ts">
+import { nextTick, ref, watch } from 'vue'
+import { useI18n } from 'vue-i18n'
+import { useAssistantStore } from '@/stores/assistant'
+import ResourceIcon from '@/components/icons/ResourceIcon.vue'
+
+const props = defineProps<{ kind: 'agent' | 'automation' }>()
+const visible = defineModel<boolean>('visible', { default: false })
+const emit = defineEmits<{ manual: [] }>()
+const { t } = useI18n()
+const assistant = useAssistantStore()
+const description = ref('')
+const submitting = ref(false)
+watch(visible, value => { if (value) description.value = '' })
+
+function manual() {
+ visible.value = false
+ emit('manual')
+}
+
+async function create() {
+ if (!description.value.trim() || submitting.value) return
+ submitting.value = true
+ const query = t(`assistant.prompts.create${props.kind === 'agent' ? 'Agent' : 'Automation'}`, {
+ request: description.value.trim(), timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ })
+ visible.value = false
+ await nextTick()
+ assistant.setPageSelection(null)
+ assistant.restorePageContext()
+ assistant.ask(query)
+ submitting.value = false
+}
+</script>
+
+<style lang="less">
+.t-dialog.assistant-create-dialog {
+ display: flex;
+ flex-direction: column;
+ max-width: calc(100vw - var(--assistant-dock-width, 0px) - 32px);
+ max-height: calc(100dvh - 48px);
+ box-sizing: border-box;
+ padding: 0;
+ overflow: hidden;
+ border: 1px solid var(--td-component-stroke);
+ border-radius: var(--app-radius-xl);
+
+ .t-dialog__header {
+ flex-shrink: 0;
+ padding: 20px 52px 0 24px;
+ }
+
+ .t-dialog__body {
+ min-height: 0;
+ padding: 12px 24px 24px;
+ }
+
+ .t-dialog__footer {
+ box-sizing: border-box;
+ flex-shrink: 0;
+ padding: 16px 24px;
+ border-top: 1px solid var(--td-component-stroke);
+ }
+
+ .assistant-create__actions .t-button + .t-button {
+ margin-left: 0;
+ }
+
+}
+</style>
+
+<style scoped lang="less">
+.assistant-create {
+ &__close {
+ position: absolute;
+ top: 16px;
+ right: 16px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 32px;
+ height: 32px;
+ padding: 0;
+ border: 0;
+ border-radius: var(--app-radius-sm);
+ background: transparent;
+ color: var(--td-text-color-secondary);
+ cursor: pointer;
+ transition: background var(--app-motion-base) ease, color var(--app-motion-base) ease;
+
+ &:hover {
+ background: var(--td-bg-color-container-hover);
+ color: var(--td-text-color-primary);
+ }
+
+ &:focus-visible {
+ outline: 2px solid var(--td-brand-color);
+ outline-offset: 2px;
+ }
+ }
+
+ &__heading {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ color: var(--td-text-color-primary);
+ font-size: var(--app-text-xl);
+ font-weight: 600;
+ line-height: 24px;
+ }
+
+ &__icon {
+ flex-shrink: 0;
+ color: var(--td-text-color-secondary);
+ }
+
+ &__hint {
+ margin: 0 0 20px;
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-md);
+ line-height: 1.6;
+ }
+
+ &__label {
+ display: block;
+ margin-bottom: 8px;
+ color: var(--td-text-color-primary);
+ font-size: var(--app-text-base);
+ font-weight: 500;
+ }
+
+ &__field {
+ display: block;
+ }
+
+ :deep(.t-textarea__inner) {
+ padding: 10px 12px;
+ border-radius: var(--app-radius-sm);
+ font-size: var(--app-text-base);
+ line-height: 22px;
+ }
+
+ &__actions {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ flex-wrap: wrap;
+ gap: 8px;
+ }
+}
+</style>
diff --git a/frontend/src/components/assistant/AssistantLauncher.vue b/frontend/src/components/assistant/AssistantLauncher.vue
index 13b54e3f7..615d9df50 100644
--- a/frontend/src/components/assistant/AssistantLauncher.vue
+++ b/frontend/src/components/assistant/AssistantLauncher.vue
@@ -1,17 +1,15 @@
<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>
+ <AssistantButton v-if="assistant.entry === 'launcher' && !assistant.visible" class="assistant-launcher"
+ :label="name" :icon-size="18" @click="assistant.open()" />
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAssistantStore } from '@/stores/assistant'
+import AssistantButton from './AssistantButton.vue'
const { t } = useI18n()
const assistant = useAssistantStore()
@@ -24,12 +22,11 @@ const name = computed(() => assistant.displayName || t('assistant.title'))
top: 50%;
right: 0;
z-index: 1400;
- display: inline-flex;
- align-items: center;
+ justify-content: flex-start;
gap: 6px;
max-width: 36px;
height: 36px;
- padding: 0 10px;
+ padding: 0 8px;
box-sizing: border-box;
overflow: hidden;
border: 1px solid var(--td-component-stroke);
@@ -37,27 +34,16 @@ const name = computed(() => assistant.displayName || t('assistant.title'))
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;
+ transition: max-width var(--app-motion-base) ease, box-shadow var(--app-motion-fast) ease,
+ background var(--app-motion-fast) ease, color 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;
+ :deep(.assistant-button__label) {
+ font-size: var(--app-text-sm);
+ }
}
</style>
diff --git a/frontend/src/components/assistant/AssistantPanel.test.ts b/frontend/src/components/assistant/AssistantPanel.test.ts
index 3ac13f337..2615e2d3f 100644
--- a/frontend/src/components/assistant/AssistantPanel.test.ts
+++ b/frontend/src/components/assistant/AssistantPanel.test.ts
@@ -15,6 +15,7 @@ const panelScript = compileScript(descriptor, { id: 'assistant-panel-test', inli
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')
+const dragScript = readFileSync(new URL('../../composables/useFloatingPreviewDrag.ts', import.meta.url), 'utf8')
function evaluate(source: string, dependencies: Record<string, unknown>, globals = {}) {
const exports: any = {}
@@ -87,6 +88,11 @@ async function fixture(
return () => null
},
})
+ const viewport = { innerWidth: 1440, innerHeight: 1000, addEventListener() {}, removeEventListener() {} }
+ const floatingDrag = evaluate(dragScript, { vue }, {
+ window: viewport,
+ ResizeObserver: class { observe() {} disconnect() {} },
+ })
const component = evaluate(panelScript, {
vue,
'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
@@ -97,8 +103,10 @@ async function fixture(
'@/views/chat/index.vue': ChatView,
'@/views/chat/components/ChildAgentTabBar.vue': emptyComponent,
'@/composables/useChildAgentTabs': childAgentTabs,
+ '@/composables/useFloatingPreviewDrag': floatingDrag,
'@/components/Input-field.vue': emptyComponent,
'@/components/PanelResizeHandle.vue': emptyComponent,
+ '@/components/icons/ResourceIcon.vue': emptyComponent,
'./AssistantContextMenu.vue': emptyComponent,
'./AssistantSelectionChip.vue': emptyComponent,
'./AssistantAccessPicker.vue': emptyComponent,
@@ -126,7 +134,7 @@ async function fixture(
deleted.push(id)
},
},
- }, { window: { addEventListener() {}, removeEventListener() {} } }).default
+ }, { window: viewport }).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) => {
@@ -145,6 +153,7 @@ async function fixture(
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,
+ querySelector: selector => selector === 'body' ? body : null,
})
const app = renderer.createApp(component)
app.use(storeRoot)
@@ -153,7 +162,10 @@ async function fixture(
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()
+ const body = node('body')
+ const root = node('app-root')
+ root.parent = body
+ body.children.push(root)
app.mount(root)
const findAll = (predicate: (node: HostNode) => boolean): HostNode[] => {
const found: HostNode[] = []
@@ -161,7 +173,7 @@ async function fixture(
if (predicate(node)) found.push(node)
node.children.forEach(walk)
}
- walk(root)
+ walk(body)
return found
}
const click = async (label: string) => {
@@ -188,6 +200,156 @@ test('layout and width persist, with the width kept within bounds', async () =>
} finally { f.close() }
})
+test('floating panels escape the app root without remounting the conversation', async () => {
+ const f = await fixture()
+ try {
+ f.assistant.open({ query: 'Explain this connection error' })
+ await flush()
+ const panel = f.findAll(node => node.tag === 'aside')[0]
+ assert.equal(panel.parent?.tag, 'app-root')
+ f.assistant.setLayout('floating')
+ await flush()
+ assert.equal(panel.parent?.tag, 'body')
+ f.assistant.setLayout('docked')
+ await flush()
+ assert.equal(panel.parent?.tag, 'app-root')
+ assert.equal(f.mounted.length, 1)
+ assert.equal(f.sent.length, 1)
+ } finally { f.close() }
+})
+
+test('the floating header moves the panel without intercepting controls or remounting the conversation', async () => {
+ const f = await fixture()
+ try {
+ f.assistant.open({ query: 'Keep this conversation running' })
+ await flush()
+ const panel = f.findAll(node => node.tag === 'aside')[0]
+ const header = f.findAll(node => node.tag === 'header')[0]
+ Object.defineProperties(panel, {
+ offsetWidth: { get: () => parseFloat(panel.props.style.width) },
+ offsetHeight: { value: 720 },
+ offsetLeft: { get: () => 1440 - parseFloat(panel.props.style.width) - parseFloat(panel.props.style.right || '12') },
+ offsetTop: { get: () => parseFloat(panel.props.style.top || '268') },
+ getBoundingClientRect: { value: () => ({ width: parseFloat(panel.props.style.width) }) },
+ })
+ let captured: number | null = null
+ Object.assign(header, {
+ setPointerCapture: (id: number) => { captured = id },
+ hasPointerCapture: (id: number) => captured === id,
+ releasePointerCapture: () => { captured = null },
+ })
+ const pointer = (clientX: number, clientY: number, control = false) => ({
+ clientX, clientY, pointerId: 1, isPrimary: true, button: 0,
+ currentTarget: header, target: { closest: () => control ? {} : null }, preventDefault() {},
+ })
+ header.props.onPointerdown(pointer(1000, 280))
+ assert.equal(captured, null, 'docked headers cannot drag')
+ f.assistant.setLayout('floating')
+ await flush()
+ header.props.onPointerdown(pointer(1000, 280, true))
+ assert.equal(captured, null, 'buttons and conversation tabs retain their normal interactions')
+ header.props.onPointerdown(pointer(1000, 280))
+ header.props.onPointermove(pointer(800, 180))
+ await flush()
+ assert.equal(captured, 1)
+ assert.match(panel.props.class, /is-dragging/)
+ assert.equal(panel.props.style.right, '212px')
+ assert.equal(panel.props.style.top, '168px')
+ header.props.onPointerup(pointer(800, 180))
+ await flush()
+ assert.equal(captured, null)
+ assert.doesNotMatch(panel.props.class, /is-dragging/)
+
+ f.assistant.close()
+ await flush()
+ f.assistant.open()
+ await flush()
+ assert.equal(panel.props.style.right, '212px')
+ assert.equal(panel.props.style.top, '168px')
+ f.assistant.setLayout('docked')
+ await flush()
+ assert.equal(panel.props.style.right, undefined)
+ assert.equal(panel.props.style.top, undefined)
+ assert.equal(f.mounted.length, 1)
+ assert.equal(f.sent.length, 1)
+ } finally { f.close() }
+})
+
+for (const existing of [false, true]) {
+ test(`contextual actions open inside the ${existing ? 'existing conversation' : 'welcome panel'} and send only on selection`, async () => {
+ let creations = 0
+ const f = await fixture(async () => { creations++; return { data: { id: 'new-session' } } })
+ try {
+ if (existing) f.assistant.setSession('ongoing-session')
+ f.assistant.publishPageContext(Symbol(), { knowledgeBaseId: 'kb-a', knowledgeId: 'document-a' })
+ f.assistant.setPageSelection({ text: 'Selected content', field: 'Document' })
+ await flush()
+ const mounts = f.mounted.length
+ await f.click('assistant.history')
+ f.assistant.showActionSuggestions({ label: 'Read this document', actions: [
+ { key: 'summary', label: 'Summarize', query: 'Summarize document-a' },
+ { key: 'compare', label: 'Compare', query: 'Compare documents', disabled: true },
+ ] })
+ await flush()
+ assert.equal(f.assistant.visible, true)
+ assert.equal(creations, 0, 'opening actions must not create a conversation or send a prompt')
+ assert.equal(f.sent.length, 0)
+ assert.equal(f.mounted.length, mounts, 'existing conversations stay mounted')
+ assert.equal(f.findAll(node => node.props.class === 'assistant-history').length, 0)
+ const buttons = f.findAll(node => node.tag === 'button')
+ const summary = buttons.find(node => node.text === 'Summarize')
+ const compare = buttons.find(node => node.text === 'Compare')
+ assert.ok(summary)
+ assert.equal(compare?.props.disabled, true)
+ f.assistant.askSuggestedAction('compare')
+ f.assistant.askSuggestedAction('missing')
+ assert.equal(f.assistant.queuedMessage, null)
+ assert.equal(creations, 0)
+ summary.props.onClick()
+ await flush()
+ assert.equal(f.assistant.actionSuggestions, null)
+ if (existing) {
+ assert.equal(f.assistant.sessionId, 'ongoing-session')
+ assert.equal(f.assistant.queuedMessage.query, 'Summarize document-a')
+ assert.equal(creations, 0)
+ } else {
+ assert.equal(creations, 1)
+ assert.equal(f.sent[0].query, 'Summarize document-a')
+ assert.equal(f.sent[0].scope.pageContext.knowledge_id, 'document-a')
+ assert.equal(f.sent[0].scope.pageContext.selection.text, 'Selected content')
+ }
+ } finally { f.close() }
+ })
+}
+
+test('contextual actions expire when their page, conversation, workspace or access changes', async () => {
+ const f = await fixture()
+ try {
+ const owner = Symbol()
+ f.assistant.publishPageContext(owner, { knowledgeBaseId: 'kb-a', knowledgeId: 'document-a' })
+ const suggest = () => f.assistant.showActionSuggestions({ label: 'Document actions', actions: [
+ { key: 'summary', label: 'Summarize', query: 'Summarize document-a' },
+ ] })
+ for (const change of [
+ () => f.assistant.publishPageContext(owner, { knowledgeBaseId: 'kb-a', knowledgeId: 'document-b' }),
+ () => f.assistant.setPageView('Another dialog'),
+ () => f.assistant.dismissPageContext(),
+ () => f.assistant.startNewConversation(),
+ () => f.assistant.setSession('another-session'),
+ () => { f.auth.effectiveTenantId = 2 },
+ () => f.assistant.setPageAccess(false),
+ ]) {
+ suggest()
+ assert.ok(f.assistant.actionSuggestions)
+ change()
+ await flush()
+ assert.equal(f.assistant.actionSuggestions, null)
+ }
+ suggest()
+ assert.equal(f.assistant.actionSuggestions, null, 'page access must be enabled')
+ } 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 {
diff --git a/frontend/src/components/assistant/AssistantPanel.vue b/frontend/src/components/assistant/AssistantPanel.vue
index d8e7254ae..337c12585 100644
--- a/frontend/src/components/assistant/AssistantPanel.vue
+++ b/frontend/src/components/assistant/AssistantPanel.vue
@@ -1,18 +1,22 @@
<template>
+ <!-- Floating panels must escape the app root's stacking context to sit above body-attached drawers. -->
+ <Teleport to="body" :disabled="effectiveLayout === 'docked'">
<!-- 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"
+ <aside ref="panelElement" class="assistant-panel"
+ :class="[`is-${effectiveLayout}`, { 'is-open': assistant.visible, 'is-resizing': resizing, 'is-dragging': dragging }]"
+ :style="[{ width: `${panelWidth}px` }, effectiveLayout === 'floating' ? positionStyle : {}]" 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">
+ <header class="assistant-panel__header" @pointerdown="startPanelDrag" @pointermove="moveDrag"
+ @pointerup="stopDrag" @pointercancel="stopDrag" @lostpointercapture="stopDrag">
<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__header-icon" aria-hidden="true"><ResourceIcon type="assistant" :size="16" /></span>
<span class="assistant-panel__title">{{ assistantName }}</span>
</template>
</ChildAgentTabBar>
@@ -66,6 +70,20 @@
<t-loading v-else-if="historyLoading" size="small" />
</div>
<div v-show="!showHistory" class="assistant-panel__conversation">
+ <section v-if="assistant.actionSuggestions && assistant.sessionId" class="assistant-suggestions"
+ :aria-label="assistant.actionSuggestions.label">
+ <div class="assistant-suggestions__header">
+ <h3>{{ assistant.actionSuggestions.label }}</h3>
+ <button type="button" class="assistant-panel__action" :aria-label="t('common.close')"
+ @click="assistant.clearActionSuggestions()"><t-icon name="close" size="14px" /></button>
+ </div>
+ <p>{{ t('assistant.chooseAction') }}</p>
+ <div class="assistant-starters">
+ <button v-for="action in assistant.actionSuggestions.actions" :key="action.key" type="button"
+ class="assistant-starter" :disabled="starting || action.disabled"
+ @click="assistant.askSuggestedAction(action.key)">{{ action.label }}</button>
+ </div>
+ </section>
<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"
@@ -92,11 +110,16 @@
<div v-else class="assistant-welcome">
<div class="assistant-welcome-body">
<div class="assistant-welcome-icon">
- <t-icon name="compass" size="22px" />
+ <ResourceIcon type="assistant" :size="22" />
+ </div>
+ <h3 class="assistant-welcome-title">{{ assistant.actionSuggestions?.label || t('assistant.welcomeTitle') }}</h3>
+ <p class="assistant-welcome-desc">{{ assistant.actionSuggestions ? t('assistant.chooseAction') : welcomeDescription }}</p>
+ <div v-if="assistant.actionSuggestions" class="assistant-starters">
+ <button v-for="action in assistant.actionSuggestions.actions" :key="action.key" type="button"
+ class="assistant-starter" :disabled="starting || action.disabled"
+ @click="assistant.askSuggestedAction(action.key)">{{ action.label }}</button>
</div>
- <h3 class="assistant-welcome-title">{{ t('assistant.welcomeTitle') }}</h3>
- <p class="assistant-welcome-desc">{{ welcomeDescription }}</p>
- <div class="assistant-starters">
+ <div v-else class="assistant-starters">
<button v-for="starter in starters" :key="starter" type="button" class="assistant-starter"
:disabled="starting" @click="startConversation(starter)">
{{ starter }}
@@ -122,6 +145,7 @@
</div>
</div>
</aside>
+ </Teleport>
</template>
<script setup lang="ts">
@@ -131,8 +155,10 @@ 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 { useFloatingPreviewDrag } from '@/composables/useFloatingPreviewDrag'
import InputField from '@/components/Input-field.vue'
import PanelResizeHandle from '@/components/PanelResizeHandle.vue'
+import ResourceIcon from '@/components/icons/ResourceIcon.vue'
import AssistantContextMenu from './AssistantContextMenu.vue'
import AssistantSelectionChip from './AssistantSelectionChip.vue'
import AssistantAccessPicker from './AssistantAccessPicker.vue'
@@ -173,6 +199,15 @@ 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 panelElement = ref<HTMLElement | null>(null)
+const { positionStyle, dragging, startDrag, moveDrag, stopDrag } = useFloatingPreviewDrag(
+ computed(() => assistant.visible && effectiveLayout.value === 'floating' ? panelElement.value : null), 'viewport',
+)
+
+function startPanelDrag(event: PointerEvent) {
+ if (effectiveLayout.value !== 'floating' || (event.target as Element).closest('button, a, input, select, textarea, [role="button"], [role="tab"]')) return
+ startDrag(event)
+}
const panelWidth = computed(() => {
const room = effectiveLayout.value === 'docked'
@@ -238,6 +273,7 @@ const starters = computed(() => {
// 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 = () => {
+ assistant.clearActionSuggestions()
const context = assistant.contextAttached ? assistant.pageContext : null
const title = assistant.contextAttached ? assistant.pageTitle : ''
const view = assistant.contextAttached ? assistant.pageView : ''
@@ -261,8 +297,10 @@ const hostScope = () => {
const welcomeInput = ref<{ focusInput?: () => void } | null>(null)
watch(() => assistant.focusRequest, () => {
+ showHistory.value = false
+ childTabs.select('')
if (!assistant.sessionId) welcomeInput.value?.focusInput?.()
-})
+}, { flush: 'post' })
async function startConversation(query: string, focus?: AssistantOpenRequest['focus']) {
const text = query.trim()
@@ -453,20 +491,27 @@ onUnmounted(() => {
border-left: 1px solid var(--td-component-stroke);
}
- // Above page drawers (1500), below dialogs and the settings shell; no mask.
+ // Above document/model drawers (2100/2300), below confirmation dialogs (2500).
&.is-floating {
position: fixed;
- top: 12px;
right: 12px;
bottom: 12px;
- z-index: 1600;
+ height: min(720px, calc(100% - 24px));
+ max-width: calc(100% - 24px);
+ z-index: 2400;
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);
+ .assistant-panel__header {
+ cursor: grab;
+ touch-action: none;
+ user-select: none;
+ }
+
+ &.is-dragging .assistant-panel__header {
+ cursor: grabbing;
}
}
@@ -479,18 +524,6 @@ onUnmounted(() => {
}
}
-@keyframes assistant-panel-in {
- from {
- opacity: 0;
- transform: translateX(16px);
- }
-
- to {
- opacity: 1;
- transform: none;
- }
-}
-
.assistant-composer-context {
display: flex;
align-items: center;
@@ -715,14 +748,170 @@ onUnmounted(() => {
}
}
+.assistant-suggestions {
+ flex-shrink: 0;
+ padding: 16px;
+ border-bottom: 1px solid var(--td-component-stroke);
+
+ &__header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+
+ h3 {
+ margin: 0;
+ font-size: var(--app-text-base);
+ font-weight: 500;
+ color: var(--td-text-color-primary);
+ }
+ }
+
+ p {
+ margin: 4px 0 0;
+ font-size: var(--app-text-sm);
+ line-height: 1.6;
+ color: var(--td-text-color-secondary);
+ }
+
+ .assistant-starters {
+ justify-content: flex-start;
+ }
+}
+
// Same inset as the composer inside a conversation.
.assistant-welcome-composer {
+ margin-top: auto;
flex-shrink: 0;
padding: 12px 16px max(8px, env(safe-area-inset-bottom));
}
+
+// Opening only changes presentation; the mounted conversation keeps streaming.
+@media (prefers-reduced-motion: no-preference) {
+ .assistant-panel.is-open {
+ animation: assistant-panel-in var(--app-motion-slow) cubic-bezier(0.16, 1, 0.3, 1);
+
+ &::before,
+ &::after {
+ content: '';
+ position: absolute;
+ inset: 0;
+ z-index: 1;
+ padding: 1px;
+ border-radius: inherit;
+ pointer-events: none;
+ opacity: 0;
+ background: conic-gradient(from var(--assistant-border-angle),
+ transparent 0deg 260deg,
+ color-mix(in srgb, var(--td-brand-color) 15%, transparent) 300deg,
+ color-mix(in srgb, var(--td-brand-color) 70%, transparent) 340deg,
+ var(--td-brand-color) 355deg,
+ transparent 360deg);
+ -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
+ mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
+ -webkit-mask-composite: xor;
+ mask-composite: exclude;
+ animation: assistant-panel-glow calc(var(--app-motion-slow) * 6) linear var(--app-motion-instant);
+ }
+
+ &::before {
+ padding: 4px;
+ filter: blur(3px);
+ }
+
+ .assistant-panel__header-icon,
+ .assistant-welcome-icon {
+ animation: assistant-icon-in calc(var(--app-motion-base) + var(--app-motion-slow)) ease-out backwards;
+ }
+
+ .assistant-welcome-icon {
+ animation-delay: var(--app-motion-instant);
+ }
+
+ .assistant-welcome-title,
+ .assistant-welcome-desc,
+ .assistant-welcome-body > .assistant-starters,
+ .assistant-welcome-composer,
+ .assistant-suggestions {
+ animation: assistant-content-in var(--app-motion-slow) cubic-bezier(0.16, 1, 0.3, 1) backwards;
+ animation-delay: var(--app-motion-instant);
+ }
+
+ .assistant-welcome-desc {
+ animation-delay: var(--app-motion-fast);
+ }
+
+ .assistant-welcome-body > .assistant-starters {
+ animation-delay: var(--app-motion-base);
+ }
+ }
+}
+
+@keyframes assistant-panel-glow {
+ from {
+ --assistant-border-angle: 0deg;
+ opacity: 0;
+ }
+
+ 12%, 80% { opacity: 0.65; }
+
+ to {
+ --assistant-border-angle: 360deg;
+ opacity: 0;
+ }
+}
+
+@keyframes assistant-panel-in {
+ from {
+ opacity: 0;
+ transform: translateX(24px);
+ }
+
+ to {
+ opacity: 1;
+ transform: none;
+ }
+}
+
+@keyframes assistant-content-in {
+ from {
+ opacity: 0;
+ transform: translateY(8px);
+ }
+
+ to {
+ opacity: 1;
+ transform: none;
+ }
+}
+
+@keyframes assistant-icon-in {
+ from {
+ opacity: 0;
+ transform: scale(0.88);
+ }
+
+ 45% {
+ opacity: 1;
+ transform: scale(1.04);
+ box-shadow: 0 0 16px color-mix(in srgb, var(--td-brand-color) 22%, transparent);
+ }
+
+ to {
+ opacity: 1;
+ transform: none;
+ box-shadow: none;
+ }
+}
</style>
<style lang="less">
+@property --assistant-border-angle {
+ syntax: '<angle>';
+ inherits: false;
+ initial-value: 0deg;
+}
+
html.has-assistant-dock {
.t-drawer:not(.t-drawer--attach):not(.chat-artifacts-drawer),
.t-dialog__ctx--fixed .t-dialog__mask,
diff --git a/frontend/src/components/assistant/AssistantSelectionBubble.vue b/frontend/src/components/assistant/AssistantSelectionBubble.vue
index bf0ce237f..1d4c0e06d 100644
--- a/frontend/src/components/assistant/AssistantSelectionBubble.vue
+++ b/frontend/src/components/assistant/AssistantSelectionBubble.vue
@@ -3,9 +3,7 @@
<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>
+ <AssistantButton :label="t('assistant.bubble.ask')" @click="run('ask')" />
<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)">
@@ -19,6 +17,7 @@
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAssistantStore } from '@/stores/assistant'
+import AssistantButton from './AssistantButton.vue'
import { selectedTextControl } from '@/utils/pageAwareness'
const QUICK_ACTIONS = ['polish', 'rewrite', 'translate', 'continue'] as const
@@ -123,24 +122,31 @@ onUnmounted(() => {
display: inline-flex;
align-items: center;
gap: 4px;
- height: 28px;
+ height: 26px;
padding: 0 8px;
border: 0;
- border-radius: var(--td-radius-medium);
+ border-radius: var(--app-radius-sm);
background: transparent;
- color: var(--td-text-color-primary);
+ color: var(--td-text-color-secondary);
font: inherit;
font-size: var(--app-text-sm);
white-space: nowrap;
cursor: pointer;
+ transition: background var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
&:hover {
background: var(--td-bg-color-container-hover);
+ color: var(--td-brand-color);
}
- &.is-primary {
+ &:active {
+ background: var(--td-bg-color-container-active);
color: var(--td-brand-color);
- font-weight: 500;
+ }
+
+ &:focus-visible {
+ outline: 2px solid var(--td-brand-color);
+ outline-offset: 2px;
}
}
diff --git a/frontend/src/components/assistant/AssistantWorkflows.test.ts b/frontend/src/components/assistant/AssistantWorkflows.test.ts
new file mode 100644
index 000000000..a28d4a983
--- /dev/null
+++ b/frontend/src/components/assistant/AssistantWorkflows.test.ts
@@ -0,0 +1,92 @@
+import assert from 'node:assert/strict'
+import test, { type TestContext } from 'node:test'
+import { reactive, nextTick } from 'vue'
+import { fixture } from '../../test-utils/vueFixture.ts'
+
+function setup(t: TestContext, file: string, props: Record<string, unknown>) {
+ const calls: Array<[string, unknown?]> = []
+ const assistant = {
+ pageAccess: true,
+ setPageSelection: (value: unknown) => calls.push(['selection', value]),
+ restorePageContext: () => calls.push(['context']),
+ ask: (value: string) => calls.push(['ask', value]),
+ focusComposer: () => calls.push(['focus']),
+ showActionSuggestions: (value: unknown) => calls.push(['suggestions', value]),
+ }
+ const state = reactive(props)
+ const { vm } = fixture(t).component(new URL(file, import.meta.url), {
+ '@/stores/assistant': { useAssistantStore: () => assistant },
+ 'vue-i18n': { useI18n: () => ({ t: (key: string, params?: unknown) => JSON.stringify({ key, params }) }) },
+ }, state)
+ return { vm, calls, assistant, state }
+}
+
+test('opening the assistant offers actions without sending and retains the clicked scope', async t => {
+ let message = 'old'
+ const f = setup(t, './AssistantActionsButton.vue', {
+ label: 'Actions', selection: { text: 'Selected answer' },
+ actions: [{ key: 'doc', label: 'Document', query: 'Use message-1' }],
+ onBeforeOpen: () => { nextTick(() => { message = 'message-1' }) },
+ })
+ f.assistant.showActionSuggestions = suggestions => f.calls.push(['suggestions', { suggestions, message }])
+ const pending = f.vm.openAssistant()
+ ;(f.state.selection as { text: string }).text = 'Another answer'
+ ;(f.state.actions as { query: string }[])[0].query = 'Use message-2'
+ await pending
+ assert.deepEqual(f.calls.map(([name]) => name), ['selection', 'context', 'suggestions'])
+ assert.deepEqual({ ...f.calls[0][1] as object }, { text: 'Selected answer' })
+ assert.equal(JSON.stringify(f.calls[2][1]), JSON.stringify({
+ suggestions: { label: 'Actions', actions: [{ key: 'doc', label: 'Document', query: 'Use message-1' }] },
+ message: 'message-1',
+ }))
+})
+
+test('assistant entries honor access and disabled states and clear stale selections on open', async t => {
+ const actions = [{ key: 'compare', label: 'Compare', query: 'Compare', disabled: true }]
+ const f = setup(t, './AssistantActionsButton.vue', {
+ label: 'Actions', actions,
+ })
+ f.assistant.pageAccess = false
+ await f.vm.openAssistant()
+ f.assistant.pageAccess = true
+ f.vm.$.props.disabled = true
+ await nextTick()
+ await f.vm.openAssistant()
+ assert.equal(f.calls.length, 0)
+ f.vm.$.props.disabled = false
+ await nextTick()
+ await f.vm.openAssistant()
+ assert.equal(JSON.stringify(f.calls), JSON.stringify([
+ ['selection', null], ['context'], ['suggestions', { label: 'Actions', actions }],
+ ]))
+})
+
+for (const kind of ['agent', 'automation']) {
+ test(`${kind} creation sends the entered request once after closing the dialog`, async t => {
+ const updates: boolean[] = []
+ const f = setup(t, './AssistantCreateDialog.vue', {
+ visible: true, kind, 'onUpdate:visible': (value: boolean) => updates.push(value),
+ })
+ f.vm.description = ' Summarize product updates '
+ const pending = f.vm.create()
+ await f.vm.create()
+ await pending
+ assert.deepEqual(updates, [false])
+ assert.deepEqual(f.calls.map(([name]) => name), ['selection', 'context', 'ask'])
+ const query = JSON.parse(f.calls[2][1] as string)
+ assert.equal(query.key, `assistant.prompts.create${kind === 'agent' ? 'Agent' : 'Automation'}`)
+ assert.equal(query.params.request, 'Summarize product updates')
+ assert.ok(query.params.timezone)
+ assert.equal(f.calls[0][1], null)
+ })
+}
+
+test('empty creation requests and manual configuration never send an assistant message', async t => {
+ let manual = 0
+ const f = setup(t, './AssistantCreateDialog.vue', { visible: true, kind: 'agent', onManual: () => { manual++ } })
+ f.vm.description = ' '
+ await f.vm.create()
+ f.vm.manual()
+ assert.equal(manual, 1)
+ assert.equal(f.calls.length, 0)
+})
diff --git a/frontend/src/components/doc-content.vue b/frontend/src/components/doc-content.vue
index 168ad4b19..c243ea896 100644
--- a/frontend/src/components/doc-content.vue
+++ b/frontend/src/components/doc-content.vue
@@ -23,6 +23,7 @@ import { diffWikiLines, type WikiDiffLine } from '@/utils/wikiLineDiff';
import { useI18n } from 'vue-i18n';
import { useAuthStore } from '@/stores/auth';
import { useAssistantStore } from '@/stores/assistant';
+import AssistantActionsButton from '@/components/assistant/AssistantActionsButton.vue';
import DocumentPreview from '@/components/document-preview.vue';
import DocumentFileIcon from '@/views/knowledge/components/DocumentFileIcon.vue';
import KnowledgeProcessingTimeline from '@/components/knowledge-processing-timeline.vue';
@@ -243,6 +244,14 @@ mermaid.initialize({
const props = defineProps(["visible", "details", "knowledgeType", "sourceInfo", "canEditKB", "canDownloadKB", "parse_status", "kbId"]);
const emit = defineEmits(["closeDoc", "getDoc", "questionDeleted", "summaryStateChange"]);
const assistant = useAssistantStore();
+const readingAssistantActions = computed(() => {
+ const source = JSON.stringify({ knowledge_base_id: props.kbId, knowledge_id: props.details?.id });
+ return [
+ { key: 'summary', label: t('assistant.actions.readSummary'), query: t('assistant.prompts.readSummary', { source }) },
+ { key: 'steps', label: t('assistant.actions.readSteps'), query: t('assistant.prompts.readSteps', { source }) },
+ { key: 'faq', label: t('assistant.actions.extractFaq'), query: t('assistant.prompts.extractFaq', { source }) },
+ ];
+});
const applySummaryState = (summaryStatus?: string, description?: string) => {
if (typeof summaryStatus === 'string' && summaryStatus) {
@@ -1605,12 +1614,9 @@ const handleChunkPageChange = (pageInfo: { current: number }) => {
<t-icon name="chart-line" size="16px" />
</template>
</t-button>
- <t-button v-if="details.id" class="header-action-btn" size="small" variant="text" shape="square"
- theme="default" :title="$t('assistant.askAboutDocument', { name: assistant.displayName || $t('assistant.title') })" @click="assistant.open()">
- <template #icon>
- <t-icon name="compass" size="16px" />
- </template>
- </t-button>
+ <AssistantActionsButton v-if="details.id" icon-only
+ :label="$t('assistant.askAboutDocument', { name: assistant.displayName || $t('assistant.title') })"
+ :actions="readingAssistantActions" />
</div>
</div>
</template>
diff --git a/frontend/src/components/icons/ResourceIcon.vue b/frontend/src/components/icons/ResourceIcon.vue
index e56c4fa65..9a164974d 100644
--- a/frontend/src/components/icons/ResourceIcon.vue
+++ b/frontend/src/components/icons/ResourceIcon.vue
@@ -10,9 +10,10 @@ import artifactIcon from '@/assets/img/artifact.svg'
import organizationIcon from '@/assets/img/organization.svg'
import toolboxIcon from '@/assets/img/toolbox.svg'
import automationIcon from '@/assets/img/automation.svg'
+import assistantIcon from '@/assets/img/assistant.svg'
const props = withDefaults(defineProps<{
- type: 'knowledge' | 'agent' | 'artifact' | 'organization' | 'toolbox' | 'automation'
+ type: 'knowledge' | 'agent' | 'artifact' | 'organization' | 'toolbox' | 'automation' | 'assistant'
size?: number
}>(), { size: 20 })
@@ -24,6 +25,7 @@ const icons = {
organization: organizationIcon,
toolbox: toolboxIcon,
automation: automationIcon,
+ assistant: assistantIcon,
}
const iconStyle = computed(() => ({
width: `${props.size}px`,
diff --git a/frontend/src/components/knowledge-processing-timeline.vue b/frontend/src/components/knowledge-processing-timeline.vue
index 4c24cfc93..edba4adf8 100644
--- a/frontend/src/components/knowledge-processing-timeline.vue
+++ b/frontend/src/components/knowledge-processing-timeline.vue
@@ -2,6 +2,7 @@
import { ref, reactive, onMounted, onBeforeUnmount, watch, computed, nextTick } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
+import AssistantActionButton from '@/components/assistant/AssistantActionButton.vue'
import { copyWithToast } from '@/utils/clipboard'
import { getKnowledgeSpans, reparseKnowledge, cancelKnowledgeParse, getKnowledgeDetails } from '@/api/knowledge-base/index'
import {
@@ -1707,8 +1708,11 @@ const processConfigLines = computed<string[]>(() => {
<div v-if="localizedErrorSuggestion(data.last_error.error_code)" class="kp-err-hint">
{{ localizedErrorSuggestion(data.last_error.error_code) }}
</div>
- <div v-if="data.parse_status === 'failed'" class="kp-err-actions">
- <button type="button" class="kp-err-btn" @click="onRetry">
+ <div class="kp-err-actions">
+ <AssistantActionButton :label="t('assistant.actions.diagnose')"
+ :query="t('assistant.prompts.documentFailure', { title: docTitle || knowledgeId, id: knowledgeId })"
+ :selection="{ field: errorHeadline, text: [data.last_error.error_code, data.last_error.error_message].filter(Boolean).join('\n') }" />
+ <button v-if="data.parse_status === 'failed'" type="button" class="kp-err-btn" @click="onRetry">
<t-icon name="refresh" size="14px" />
<span>{{ t('knowledgeStages.retry') }}</span>
</button>
@@ -3058,6 +3062,7 @@ const processConfigLines = computed<string[]>(() => {
.kp-err-actions {
display: flex;
+ align-items: center;
gap: 8px;
margin-top: 10px;
}
diff --git a/frontend/src/components/manual-knowledge-editor.vue b/frontend/src/components/manual-knowledge-editor.vue
index 3b6a369f6..7b91edd02 100644
--- a/frontend/src/components/manual-knowledge-editor.vue
+++ b/frontend/src/components/manual-knowledge-editor.vue
@@ -1,8 +1,8 @@
<script setup lang="ts">
-import { ref, reactive, computed, watch, nextTick, onBeforeUnmount, h } from 'vue'
+import { ref, reactive, computed, watch, nextTick, onBeforeUnmount } from 'vue'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
import { marked } from 'marked'
-import { DialogPlugin, MessagePlugin, Icon as TIcon } from 'tdesign-vue-next'
+import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'
import { registerUnsavedChanges } from '@/utils/unsavedChanges'
import { useUIStore } from '@/stores/ui'
import {
@@ -18,7 +18,7 @@ import type { KnowledgeProcessOverrides } from '@/types/knowledgeProcess'
import { sanitizeHTML, safeMarkdownToHTML, hydrateProtectedFileImages } from '@/utils/security'
import { continueListOnEnter, countContent, indentOnTab } from '@/utils/markdownEditing'
import { useI18n } from 'vue-i18n'
-import { useAssistantStore } from '@/stores/assistant'
+import AssistantActionsButton from '@/components/assistant/AssistantActionsButton.vue'
interface KnowledgeBaseOption {
label: string
@@ -61,35 +61,12 @@ const uploadConfirmStore = useUploadConfirmStore()
const organizationStore = useOrganizationStore()
const chatResources = useChatResourcesStore()
const { t } = useI18n()
-const assistant = useAssistantStore()
-
-// Asks the assistant beside the editor; it writes into the editor and the
-// user saves. "open" only moves to its input box.
-const ASSISTANT_ACTIONS = ['continue', 'outline', 'polish', 'summarize'] as const
-const ASSISTANT_ACTION_ICONS: Record<typeof ASSISTANT_ACTIONS[number], string> = {
- continue: 'pen',
- outline: 'tree-list',
- polish: 'ai-edit',
- summarize: 'bulletpoint',
-}
-const menuIcon = (name: string) => () => h(TIcon, { name, size: '16px' })
-// A dropdown divider is drawn below its item, so it sits on the last action.
-const assistantMenu = computed(() => [
- ...ASSISTANT_ACTIONS.map((action, i) => ({
- content: t(`manualEditor.assistant.${action}`),
- value: action,
- prefixIcon: menuIcon(ASSISTANT_ACTION_ICONS[action]),
- divider: i === ASSISTANT_ACTIONS.length - 1,
- })),
- { content: t('manualEditor.assistant.open'), value: 'open', prefixIcon: menuIcon('chat-bubble') },
-])
-const handleAssistantMenu = (selected: unknown) => {
- const value = (selected as { value?: string } | null)?.value
- if (value === 'open') assistant.focusComposer()
- else if (ASSISTANT_ACTIONS.includes(value as typeof ASSISTANT_ACTIONS[number])) {
- assistant.ask(t(`manualEditor.assistant.prompts.${value}`))
- }
-}
+// The assistant fills the open editor; the user saves the result.
+const assistantActions = computed(() => ['continue', 'outline', 'polish', 'summarize'].map(action => ({
+ key: action,
+ label: t(`manualEditor.assistant.${action}`),
+ query: t(`manualEditor.assistant.prompts.${action}`),
+})))
const visible = computed({
get: () => uiStore.manualEditorVisible,
@@ -1080,20 +1057,8 @@ onBeforeUnmount(() => {
</template>
</div>
<div class="editor-toolbar__view">
- <t-dropdown
- v-if="assistant.pageAccess"
- :options="assistantMenu"
- trigger="click"
- :min-column-width="112"
- :popup-props="{ attach: 'body', zIndex: 2600, overlayInnerClassName: 'editor-assistant-menu' }"
- @click="(selected: unknown) => handleAssistantMenu(selected)"
- >
- <button type="button" class="toolbar-assistant" :aria-label="$t('manualEditor.assistant.tooltip')"
- @mousedown.prevent>
- <t-icon name="ai-edit" />
- <span>{{ $t('manualEditor.assistant.button') }}</span>
- </button>
- </t-dropdown>
+ <AssistantActionsButton :label="$t('manualEditor.assistant.button')"
+ :title="$t('manualEditor.assistant.tooltip')" :actions="assistantActions" @mousedown.prevent />
<t-tooltip placement="top-right" :show-arrow="false">
<template #content>
<div class="shortcut-sheet">
@@ -1438,43 +1403,6 @@ onBeforeUnmount(() => {
}
}
-.toolbar-assistant {
- display: inline-flex;
- align-items: center;
- gap: 4px;
- height: 26px;
- padding: 0 8px;
- border: none;
- 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;
- white-space: nowrap;
- cursor: pointer;
- transition: background var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
-
- .t-icon {
- color: var(--td-brand-color);
- font-size: var(--app-text-md);
- }
-
- &:hover {
- background: var(--td-bg-color-container-hover);
- color: var(--td-text-color-primary);
- }
-
- &:active {
- background: var(--td-bg-color-container-active);
- }
-
- &:focus-visible {
- outline: none;
- box-shadow: 0 0 0 2px color-mix(in srgb, var(--td-brand-color) 25%, transparent);
- }
-}
-
/* 快捷键速查:和视图切换同处工具栏右端,省掉一整条状态栏 */
.toolbar-shortcuts {
display: flex;
@@ -1735,37 +1663,6 @@ onBeforeUnmount(() => {
}
}
-/* 工具栏下拉跟工具栏同尺寸,全局下拉样式是按侧边栏菜单定的 */
-.t-popup__content.editor-assistant-menu {
- .t-dropdown__menu {
- min-width: 0;
- }
-
- .t-dropdown__item {
- padding: 5px 8px;
- line-height: 18px;
-
- .t-dropdown__item-text {
- font-size: var(--app-text-md) !important;
- line-height: 18px !important;
- }
-
- .t-dropdown__item-icon {
- margin-right: 6px;
-
- .t-icon {
- font-size: var(--app-text-base);
- width: var(--app-text-base);
- height: var(--app-text-base);
- }
- }
- }
-
- .t-divider {
- margin: 3px 6px;
- }
-}
-
.manual-editor-drawer {
/* 没有副标题的抽屉不需要 65px 的头:收一圈内边距、缩小图标徽章,
把高度还给正文。只作用于本抽屉,不动共用的 SettingDrawer。 */
diff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vue
index 24a84f6ea..1d6774223 100644
--- a/frontend/src/components/menu.vue
+++ b/frontend/src/components/menu.vue
@@ -8,10 +8,8 @@
</div>
<div class="logo_actions">
<t-tooltip v-if="assistantStore.entry === 'sidebar'" :content="assistantName" placement="bottom">
- <div class="header-icon-btn" :class="{ 'is-active': assistantStore.visible }"
- :aria-label="assistantName" @click="assistantStore.toggle()">
- <t-icon name="compass" size="18px" />
- </div>
+ <AssistantButton icon-only :icon-size="18" :label="assistantName"
+ :active="assistantStore.visible" @click="assistantStore.toggle()" />
</t-tooltip>
<t-tooltip placement="bottom">
<template #content>
@@ -84,14 +82,8 @@
</div>
</t-tooltip>
<t-tooltip v-if="assistantStore.entry === 'sidebar'" :content="assistantName" placement="right">
- <div class="menu_item menu_item--cmdk" :class="{ 'menu_item_active': assistantStore.visible }"
- :aria-label="assistantName" @click="assistantStore.toggle()">
- <div class="menu_item-box">
- <div class="menu_icon">
- <t-icon name="compass" size="18px" />
- </div>
- </div>
- </div>
+ <AssistantButton class="assistant-sidebar-entry" icon-only :icon-size="18"
+ :label="assistantName" :active="assistantStore.visible" @click="assistantStore.toggle()" />
</t-tooltip>
</div>
<div class="menu_box" :class="{ 'menu_box--sticky': item.children && !uiStore.sidebarCollapsed }"
@@ -291,6 +283,7 @@ import { useOrganizationStore } from '@/stores/organization';
import { useUIStore } from '@/stores/ui';
import { useCommandPaletteStore } from '@/stores/commandPalette';
import { useAssistantStore } from '@/stores/assistant';
+import AssistantButton from '@/components/assistant/AssistantButton.vue';
import { MessagePlugin, DialogPlugin, Icon as TIcon } from "tdesign-vue-next";
import UserMenu from '@/components/UserMenu.vue';
import TenantSelector from '@/components/TenantSelector.vue';
@@ -1841,6 +1834,13 @@ const resizeSidebar = (delta: number, keyboard: boolean) => {
flex-shrink: 0;
}
+.aside_box--collapsed .assistant-sidebar-entry {
+ display: flex;
+ width: 32px;
+ height: 32px;
+ margin: 0 auto 6px;
+}
+
.header-icon-btn {
display: flex;
align-items: center;
diff --git a/frontend/src/composables/useFloatingPreviewDrag.test.ts b/frontend/src/composables/useFloatingPreviewDrag.test.ts
index 17d33bf4e..6c3b29dbc 100644
--- a/frontend/src/composables/useFloatingPreviewDrag.test.ts
+++ b/frontend/src/composables/useFloatingPreviewDrag.test.ts
@@ -19,7 +19,10 @@ test('preview drags in both directions, stays bounded, and releases capture on t
parentNode: () => null, nextSibling: () => null,
})
const container = { clientWidth: 1000, clientHeight: 700 }
- const preview = { offsetParent: container, offsetWidth: 240, offsetHeight: 250, offsetLeft: 740, offsetTop: 434 }
+ const preview = {
+ offsetParent: container, offsetWidth: 240, offsetHeight: 250, offsetLeft: 740, offsetTop: 434,
+ getBoundingClientRect() { return { width: this.offsetWidth } },
+ }
const element = shallowRef<HTMLElement | null>(null)
let controls!: ReturnType<typeof useFloatingPreviewDrag>
let captured: number | null = null
@@ -83,3 +86,94 @@ test('preview drags in both directions, stays bounded, and releases capture on t
}
assert.equal(captured, null)
})
+
+test('floating windows drag at the app zoom level, retain their right anchor, and stay inside the viewport', async () => {
+ const originalObserver = globalThis.ResizeObserver
+ const originalWindow = globalThis.window
+ const listeners = new Set<() => void>()
+ const viewport = {
+ innerWidth: 1440, innerHeight: 1000,
+ addEventListener: (_: string, listener: () => void) => listeners.add(listener),
+ removeEventListener: (_: string, listener: () => void) => listeners.delete(listener),
+ }
+ globalThis.window = viewport as unknown as Window & typeof globalThis
+ let resize!: ResizeObserverCallback
+ globalThis.ResizeObserver = class {
+ constructor(callback: ResizeObserverCallback) { resize = callback }
+ observe() {}
+ disconnect() {}
+ } as unknown as typeof ResizeObserver
+ const renderer = createRenderer<any, any>({
+ patchProp() {}, insert() {}, remove() {}, setText() {}, setElementText() {},
+ createElement: () => ({}), createText: () => ({}), createComment: () => ({}),
+ parentNode: () => null, nextSibling: () => null,
+ })
+ const element = shallowRef<HTMLElement | null>(null)
+ let controls!: ReturnType<typeof useFloatingPreviewDrag>
+ let scale = 1
+ const preview = {
+ offsetParent: null, offsetWidth: 440, offsetHeight: 720,
+ get offsetLeft() { return viewport.innerWidth / scale - this.offsetWidth - parseFloat(controls.positionStyle.value.right || '12') },
+ get offsetTop() { return parseFloat(controls.positionStyle.value.top || '268') },
+ getBoundingClientRect() { return { width: this.offsetWidth * scale } },
+ }
+ let captured: number | null = null
+ const handle = {
+ setPointerCapture(id: number) { captured = id },
+ hasPointerCapture(id: number) { return captured === id },
+ releasePointerCapture() { captured = null },
+ }
+ const pointer = (clientX: number, clientY: number) => ({
+ clientX, clientY, pointerId: 1, isPrimary: true, button: 0,
+ currentTarget: handle, preventDefault() {},
+ } as unknown as PointerEvent)
+ const app = renderer.createApp({ setup() { controls = useFloatingPreviewDrag(element, 'viewport'); return () => null } })
+ app.mount({})
+ try {
+ element.value = preview as unknown as HTMLElement
+ await nextTick()
+ assert.deepEqual(controls.positionStyle.value, {}, 'the initial bottom-right position is preserved')
+ controls.startDrag(pointer(1000, 280))
+ controls.moveDrag(pointer(800, 180))
+ controls.stopDrag()
+ assert.deepEqual(controls.positionStyle.value, { left: 'auto', right: '212px', top: '168px', bottom: 'auto' })
+ preview.offsetWidth = 500
+ resize([], {} as ResizeObserver)
+ assert.equal(controls.positionStyle.value.right, '212px', 'resizing from the left keeps the right edge anchored')
+
+ element.value = null
+ await nextTick()
+ assert.equal(listeners.size, 0)
+ element.value = preview as unknown as HTMLElement
+ await nextTick()
+ assert.equal(controls.positionStyle.value.right, '212px', 'reopening keeps the chosen position')
+
+ scale = 1.25
+ preview.offsetHeight = 600
+ controls.startDrag(pointer(800, 200))
+ controls.moveDrag(pointer(675, 75))
+ controls.stopDrag()
+ assert.equal(controls.positionStyle.value.right, '312px')
+ assert.equal(controls.positionStyle.value.top, '68px', '125 screen pixels move 100 CSS pixels at 125% zoom')
+ controls.startDrag(pointer(800, 200))
+ controls.moveDrag(pointer(5000, -5000))
+ assert.equal(controls.positionStyle.value.right, '12px')
+ assert.equal(controls.positionStyle.value.top, '12px')
+ controls.moveDrag(pointer(-5000, 5000))
+ assert.equal(controls.positionStyle.value.right, '640px')
+ assert.equal(controls.positionStyle.value.top, '188px')
+ controls.stopDrag()
+ viewport.innerWidth = 700
+ viewport.innerHeight = 800
+ listeners.forEach(listener => listener())
+ assert.equal(controls.positionStyle.value.right, '48px')
+ assert.equal(controls.positionStyle.value.top, '28px')
+ controls.startDrag(pointer(100, 100))
+ } finally {
+ app.unmount()
+ globalThis.ResizeObserver = originalObserver
+ globalThis.window = originalWindow
+ }
+ assert.equal(captured, null)
+ assert.equal(listeners.size, 0)
+})
diff --git a/frontend/src/composables/useFloatingPreviewDrag.ts b/frontend/src/composables/useFloatingPreviewDrag.ts
index 14fba1c1d..38905faa2 100644
--- a/frontend/src/composables/useFloatingPreviewDrag.ts
+++ b/frontend/src/composables/useFloatingPreviewDrag.ts
@@ -1,21 +1,26 @@
import { computed, ref, watch, type Ref } from 'vue'
-/** Move an absolutely positioned preview within its containing panel. */
-export function useFloatingPreviewDrag(element: Ref<HTMLElement | null>) {
+/** Move a preview within its parent, or a right-anchored floating window within the viewport. */
+export function useFloatingPreviewDrag(element: Ref<HTMLElement | null>, boundary: 'parent' | 'viewport' = 'parent') {
const position = ref<{ x: number; y: number } | null>(null)
const dragging = ref(false)
- let drag: { pointerId: number; handle: HTMLElement; x: number; y: number; left: number; top: number } | null = null
+ let drag: { pointerId: number; handle: HTMLElement; x: number; y: number; horizontal: number; top: number; scale: number } | null = null
const positionStyle = computed(() => position.value
- ? { left: `${position.value.x}px`, top: `${position.value.y}px`, right: 'auto', bottom: 'auto' }
+ ? {
+ left: boundary === 'viewport' ? 'auto' : `${position.value.x}px`,
+ right: boundary === 'viewport' ? `${position.value.x}px` : 'auto',
+ top: `${position.value.y}px`, bottom: 'auto',
+ }
: {})
function constrain(x: number, y: number) {
const preview = element.value
const container = preview?.offsetParent as HTMLElement | null
- if (!preview || !container) return null
- const maxX = Math.max(0, container.clientWidth - preview.offsetWidth)
- const maxY = Math.max(0, container.clientHeight - preview.offsetHeight)
+ if (!preview?.offsetWidth || !preview.offsetHeight || (boundary === 'parent' && !container)) return null
+ const scale = preview.getBoundingClientRect().width / preview.offsetWidth || 1
+ const maxX = Math.max(0, (boundary === 'viewport' ? window.innerWidth / scale : container!.clientWidth) - preview.offsetWidth)
+ const maxY = Math.max(0, (boundary === 'viewport' ? window.innerHeight / scale : container!.clientHeight) - preview.offsetHeight)
const marginX = Math.min(12, maxX / 2)
const marginY = Math.min(12, maxY / 2)
return {
@@ -34,13 +39,16 @@ export function useFloatingPreviewDrag(element: Ref<HTMLElement | null>) {
function startDrag(event: PointerEvent) {
const preview = element.value
- if (!preview || !event.isPrimary || event.button !== 0 || drag) return
+ if (!preview?.offsetWidth || !event.isPrimary || event.button !== 0 || drag) return
const handle = event.currentTarget as HTMLElement
handle.setPointerCapture(event.pointerId)
+ // Pointer coordinates include the app's font-size zoom; offsets use CSS pixels.
+ const scale = preview.getBoundingClientRect().width / preview.offsetWidth || 1
drag = {
pointerId: event.pointerId, handle,
x: event.clientX, y: event.clientY,
- left: preview.offsetLeft, top: preview.offsetTop,
+ horizontal: boundary === 'viewport' ? window.innerWidth / scale - preview.offsetLeft - preview.offsetWidth : preview.offsetLeft,
+ top: preview.offsetTop, scale,
}
dragging.value = true
event.preventDefault()
@@ -48,22 +56,32 @@ export function useFloatingPreviewDrag(element: Ref<HTMLElement | null>) {
function moveDrag(event: PointerEvent) {
if (!drag || event.pointerId !== drag.pointerId) return
- position.value = constrain(drag.left + event.clientX - drag.x, drag.top + event.clientY - drag.y)
+ const direction = boundary === 'viewport' ? -1 : 1
+ position.value = constrain(drag.horizontal + direction * (event.clientX - drag.x) / drag.scale,
+ drag.top + (event.clientY - drag.y) / drag.scale)
}
watch(element, (preview, _, onCleanup) => {
if (!preview) return
const keepInBounds = () => {
- const x = position.value?.x ?? preview.offsetLeft
+ if (!preview.offsetWidth || !preview.offsetHeight) return
+ const scale = preview.getBoundingClientRect().width / preview.offsetWidth || 1
+ const x = position.value?.x ?? (boundary === 'viewport'
+ ? window.innerWidth / scale - preview.offsetLeft - preview.offsetWidth : preview.offsetLeft)
const y = position.value?.y ?? preview.offsetTop
const bounded = constrain(x, y)
if (bounded && (position.value || bounded.x !== x || bounded.y !== y)) position.value = bounded
}
const observer = new ResizeObserver(keepInBounds)
observer.observe(preview)
- if (preview.offsetParent) observer.observe(preview.offsetParent)
+ if (boundary === 'viewport') window.addEventListener('resize', keepInBounds)
+ else if (preview.offsetParent) observer.observe(preview.offsetParent)
keepInBounds()
- onCleanup(() => { observer.disconnect(); stopDrag() })
+ onCleanup(() => {
+ observer.disconnect()
+ if (boundary === 'viewport') window.removeEventListener('resize', keepInBounds)
+ stopDrag()
+ })
}, { flush: 'post' })
return { positionStyle, dragging, startDrag, moveDrag, stopDrag }
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 4c265277e..63c9134a2 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -6411,6 +6411,76 @@ export default {
welcomeDesc: 'Ask how WeKnora works, or have me check and handle document parsing, knowledge base activity and Wiki issues in your workspace, or create and configure agents. Whether I ask before a change depends on the access level below the input box.',
startFailed: 'Failed to start the assistant. Please try again.',
askAboutDocument: 'Ask {name}',
+ chooseAction: "Choose an action, or describe what you need.",
+ create: {
+ agentTitle: "Describe your agent",
+ agentHint: "Describe who it serves and what it should do. The assistant will choose resources and create it.",
+ agentPlaceholder: "For example: a support agent that answers product questions using our knowledge base, cites sources and acknowledges missing information.",
+ automationTitle: "Create a task with the assistant",
+ automationHint: "Describe what to do and when to run it. The assistant will turn it into an automation.",
+ automationPlaceholder: "For example: every Friday at 5 PM, summarize this week’s updates to the product knowledge base.",
+ requestLabel: "Task description",
+ manual: "Configure manually",
+ start: "Continue with assistant",
+ },
+ actions: {
+ writeAnswer: "Draft answer",
+ refineAnswer: "Improve answer",
+ processSelected: "Work with selected",
+ summarizeSelected: "Summarize selected",
+ compareDocuments: "Compare documents",
+ suggestTags: "Suggest tags",
+ organizeDocuments: "Organize folders",
+ summarizeActivity: "Summarize these {count} updates",
+ toolExamples: "Show tool examples",
+ readContent: "Read with assistant",
+ readSummary: "Extract key points",
+ readSteps: "Extract action steps",
+ extractFaq: "Extract FAQ",
+ answerToDocument: "Turn into a document",
+ answerToFaq: "Save as FAQ",
+ answerToAutomation: "Make a scheduled task",
+ analyzeRun: "Analyze result",
+ summarizeRun: "Summarize this run",
+ compareRuns: "Compare recent runs",
+ writePrompt: 'Help me write',
+ refinePrompt: 'Improve prompt',
+ diagnose: 'Diagnose',
+ suggestFaqQuestions: 'Suggest variations',
+ refineRules: 'Refine rules',
+ analyzeChunks: 'Analyze chunks',
+ },
+ prompts: {
+ startAgentCreation: "I want to create an agent using natural language. First ask whom it will serve and what it should do. Once the requirements are clear, check available models, knowledge bases, MCP services, and skills, choose suitable resources, follow the current permission rules, create the agent, and open its configuration.",
+ createAgent: "Create an agent for this request: {request}. Check available models, knowledge bases, MCP services and skills; choose suitable resources. Ask only for necessary missing information, follow the current access policy, and open its editor after creation.",
+ createAutomation: "Create a scheduled task: {request}. Use timezone {timezone} unless specified otherwise. Write self-contained instructions, validate the schedule and show upcoming run times. Follow current access rules without increasing execution permissions, then open the created task.",
+ writeFaqAnswer: "Draft an FAQ answer using the question, existing answers and verifiable sources. Ask if facts are missing. Fill only the current answer input; do not add, save or change existing answers.",
+ refineFaqAnswer: "Read the FAQ question and full answer draft. Improve clarity and tone while preserving facts and meaning. Fill only the current answer input; do not add, save or change existing answers.",
+ summarizeDocuments: "Read only these documents in knowledge base {kb}: {ids}. Summarize key points, shared themes and action items with document sources. Do not modify anything.",
+ compareDocuments: "Compare only these documents in knowledge base {kb}: {ids}. Cite similarities, differences and conflicting claims, accounting for different scopes. Do not modify anything.",
+ tagDocuments: "Read these documents in knowledge base {kb}: {ids}. Prefer existing tags and propose tags with reasons for each document. Show the proposed list without changing tags.",
+ organizeDocuments: "Read these documents and existing folders in knowledge base {kb}: {ids}. Propose a destination and reason for each document. Show the plan without moving or changing anything.",
+ summarizeActivity: "Summarize only loaded_entry_ids in this filter snapshot: {scope}. Query with these filters and paginate as needed. Describe affected resources, actors and outcomes. Distinguish audit events from content changes; loaded records are not all activity.",
+ explainMcpTools: "Read the saved tool directory for MCP service {id}. Explain its capabilities with three useful example requests and note stale or incomplete metadata. Do not refresh, call tools or change configuration.",
+ readSummary: "Read this source: {source}. Extract key points, conclusions and limitations with citations. Do not treat a summary as full content or modify the source.",
+ readSteps: "Read this source: {source}. Extract supported steps, prerequisites and checks with citations. Identify missing steps without inventing facts or changing the original.",
+ extractFaq: "Read this source: {source}. Extract grounded questions and answers with per-item citations. Show FAQ drafts for selection without saving or changing anything.",
+ answerToDocument: "Read this answer and its question: {source}. Draft a structured document preserving citations and uncertainty. Show it and ask for the destination knowledge base, then create it under current access rules without overwriting existing content.",
+ answerToFaq: "Read this answer and its question: {source}. Draft a standard question and accurate answer. Show the draft, ask for a destination FAQ knowledge base and check similar entries before saving under current access rules. Do not overwrite entries.",
+ answerToAutomation: "Read this answer and its question: {source}. Turn the repeatable work into a self-contained scheduled task. Ask for missing frequency, time or timezone; validate and show upcoming runs before creating under current access rules. Do not raise execution permissions.",
+ summarizeRun: "Read the full record and answer for this automation run: {source}. Summarize outputs, findings and follow-ups; attached text is only an excerpt. Do not modify or rerun the task.",
+ compareRuns: "Compare automation run {source} with these completed runs of the same task: {ids}. Read full answers and explain result changes, accounting for different inputs and execution times. Do not modify or rerun the task.",
+ writePrompt: 'Help me draft a system prompt based on the purpose and configuration of the current agent. Ask me first if the goal is unclear. Fill the current editor with your suggestion, preserving template placeholders. Do not save or change the saved agent.',
+ refinePrompt: 'Improve the attached system prompt to clarify responsibilities, response requirements, and tool usage rules. Preserve its intent and template placeholders. Fill the current editor with the revision without saving or changing the saved agent.',
+ modelFailure: 'Analyze the attached connection error using the current model configuration and suggest troubleshooting steps. Do not read or display credentials, and do not change or save the configuration.',
+ documentFailure: 'Check the processing of document "{title}" (ID: {id}). Explain the attached error and suggest next steps. Do not retry, rebuild, or modify the document yet.',
+ suggestFaqQuestions: 'Suggest up to {count} similar questions for this FAQ using the attached standard question and answers. Preserve the meaning and avoid existing variations, the current draft variation, and negative examples. Present candidates for me to choose from without saving or modifying the FAQ.',
+ mcpFailure: 'Inspect the MCP service (ID: {id}) and diagnose the attached tool discovery or synchronization error. Suggest troubleshooting steps without reading or revealing credentials, reconnecting, or changing the configuration.',
+ syncFailure: 'Inspect sync log {log} for data source "{source}" (ID: {id}). Use the attached error samples and failure counts to explain the cause and suggest next steps. Do not retry the sync or modify the data source.',
+ writeWikiRules: 'Draft clear rules for "{field}" based on the purpose of the current knowledge base. Ask me first if the purpose is unclear. Fill the corresponding editor field, preserving the system citation and output protocols. Do not save or reparse.',
+ refineWikiRules: 'Clarify the attached "{field}" rules while preserving their meaning. Fill the corresponding editor field, preserving the system citation and output protocols. Do not save or reparse.',
+ analyzeChunks: 'Analyze this attached chunking preview using its original-text and chunk excerpts, the parameters used for that run, and the statistics. Identify fragmented meaning or overly short or long chunks, and suggest parameter changes. Distinguish findings supported by the excerpts from those needing more source text. Do not change settings or rebuild the knowledge base.',
+ },
askAboutAnswer: 'Ask {name} about this answer',
selection: {
label: 'Selected',
diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts
index 9486a41ca..c402bd841 100644
--- a/frontend/src/i18n/locales/ja-JP.ts
+++ b/frontend/src/i18n/locales/ja-JP.ts
@@ -6411,6 +6411,76 @@ export default {
welcomeDesc: 'WeKnora の使い方にお答えするほか、ワークスペースのドキュメント解析、ナレッジベースの履歴、Wiki の問題を確認・対応し、エージェントの作成や設定もお手伝いできます。変更の前に確認するかどうかは、入力欄の下の権限レベルで決まります。',
startFailed: 'アシスタントを起動できませんでした。もう一度お試しください。',
askAboutDocument: '{name}に聞く',
+ chooseAction: "機能を選ぶか、希望する内容を入力してください。",
+ create: {
+ agentTitle: "自然言語でエージェントを作成",
+ agentHint: "利用者と目的を説明してください。アシスタントがリソースを選び、作成します。",
+ agentPlaceholder: "例:製品ナレッジベースから質問に回答し、出典を示し、不明な点は説明するサポート担当。",
+ automationTitle: "アシスタントでタスクを作成",
+ automationHint: "実行する内容と日時を入力すると、アシスタントが自動化タスクにまとめます。",
+ automationPlaceholder: "例:毎週金曜日の午後5時に、製品ナレッジベースの今週の更新をまとめる。",
+ requestLabel: "タスクの説明",
+ manual: "手動で設定",
+ start: "アシスタントに依頼",
+ },
+ actions: {
+ writeAnswer: "回答を作成",
+ refineAnswer: "回答を改善",
+ processSelected: "選択項目を処理",
+ summarizeSelected: "要点をまとめる",
+ compareDocuments: "文書を比較",
+ suggestTags: "タグを提案",
+ organizeDocuments: "フォルダーを整理",
+ summarizeActivity: "この {count} 件の更新を要約",
+ toolExamples: "使用例を見る",
+ readContent: "アシスタントで読む",
+ readSummary: "要点を抽出",
+ readSteps: "手順を整理",
+ extractFaq: "FAQ を抽出",
+ answerToDocument: "文書にまとめる",
+ answerToFaq: "FAQ として保存",
+ answerToAutomation: "定期タスクにする",
+ analyzeRun: "結果を分析",
+ summarizeRun: "今回の結果を要約",
+ compareRuns: "最近の実行と比較",
+ writePrompt: '作成を手伝う',
+ refinePrompt: 'プロンプトを改善',
+ diagnose: '原因を分析',
+ suggestFaqQuestions: '類似質問を提案',
+ refineRules: 'ルールを改善',
+ analyzeChunks: '分割結果を分析',
+ },
+ prompts: {
+ startAgentCreation: "自然言語でエージェントを作成したいです。まず対象ユーザーと実行したいタスクを質問してください。要件が明確になったら、利用可能なモデル、ナレッジベース、MCP サービス、スキルを確認して適切なリソースを選び、現在の権限に従って作成し、設定画面を開いてください。",
+ createAgent: "次の要望でエージェントを作成してください:{request}。利用可能なモデル、ナレッジベース、MCP、スキルを確認して選び、必要な不足情報だけを質問してください。現在の権限に従い、作成後に編集画面を開いてください。",
+ createAutomation: "定期タスクを作成してください:{request}。指定がなければタイムゾーンは {timezone}。単独実行できる指示にまとめ、日時を検証し次回の実行時刻を示してください。権限を引き上げず現在の規則に従い、作成後にタスクを開いてください。",
+ writeFaqAnswer: "標準質問、既存の回答、確認できる資料から FAQ の回答を作成してください。不足する事実は質問し、推測しないでください。現在の回答欄だけに入力し、追加、保存、既存回答の変更はしないでください。",
+ refineFaqAnswer: "FAQ の質問と回答草稿の全文を読み、事実と意味を保って表現を改善してください。現在の回答欄だけに戻し、追加、保存、既存回答の変更はしないでください。",
+ summarizeDocuments: "ナレッジベース {kb} の次の文書だけを読んでください:{ids}。要点、共通テーマ、対応事項を出典付きでまとめ、資料は変更しないでください。",
+ compareDocuments: "ナレッジベース {kb} の次の文書だけを比較してください:{ids}。適用範囲の違いを考慮し、共通点、相違点、矛盾を出典付きで示してください。変更はしないでください。",
+ tagDocuments: "ナレッジベース {kb} の文書 {ids} を読み、既存タグを優先して文書ごとのタグと理由を提案してください。一覧を提示し、タグは変更しないでください。",
+ organizeDocuments: "ナレッジベース {kb} の文書 {ids} と既存フォルダーを読み、文書ごとの移動先と理由を提案してください。計画だけを示し、移動や変更はしないでください。",
+ summarizeActivity: "次のフィルター情報の loaded_entry_ids だけを要約してください:{scope}。同じ条件で検索し、必要ならページを追加取得してください。対象資料、実行者、結果を示し、操作ログと本文変更を区別してください。表示済みの記録を全件とみなさないでください。",
+ explainMcpTools: "MCP サービス {id} の保存済みツール一覧を読み、機能と実用的な質問例を3つ示してください。古い情報や不足を明示し、更新、ツール実行、設定変更はしないでください。",
+ readSummary: "次の資料を読んでください:{source}。要点、結論、制限を出典付きで示してください。要約を全文とみなさず、資料を変更しないでください。",
+ readSteps: "次の資料を読み、根拠のある手順、前提、確認項目を出典付きで整理してください:{source}。不足は明示し、事実の創作や原文の変更はしないでください。",
+ extractFaq: "資料 {source} から根拠のある質問と回答を抽出し、項目ごとに出典を示してください。選択用の FAQ 草稿を提示し、保存や変更はしないでください。",
+ answerToDocument: "回答と元の質問 {source} を読み、出典と不確実性を保った文書草稿を作成してください。草稿を示して保存先のナレッジベースを確認し、現在の権限で新規作成してください。既存資料は上書きしないでください。",
+ answerToFaq: "回答と元の質問 {source} から標準質問と正確な回答を作成してください。草稿を示し、保存先 FAQ ナレッジベースを確認し、類似項目を調べて現在の権限で保存してください。既存項目は上書きしないでください。",
+ answerToAutomation: "回答と質問 {source} の反復作業を独立実行できる定期タスクにまとめてください。不足する頻度、時刻、タイムゾーンを確認し、実行予定を検証・表示して現在の権限で作成してください。実行権限は引き上げないでください。",
+ summarizeRun: "次の自動化実行の全記録と回答を読んでください:{source}。成果、発見、対応事項をまとめてください。添付文は抜粋です。タスクの変更や再実行はしないでください。",
+ compareRuns: "自動化実行 {source} と、同じタスクの完了済み実行 {ids} を比較してください。回答全文を読み、入力や実行時刻の違いを考慮して結果の変化を説明してください。変更や再実行はしないでください。",
+ writePrompt: '現在のエージェントの目的と設定に基づいてシステムプロンプトを作成してください。目的が不明な場合は先に質問してください。テンプレートのプレースホルダーを保持し、現在のエディターに提案を入力してください。保存済みのエージェントを変更・保存しないでください。',
+ refinePrompt: '添付のシステムプロンプトの役割、回答要件、ツールの使用ルールを明確にしてください。元の意図とテンプレートのプレースホルダーを保持し、修正を現在のエディターに入力してください。保存済みのエージェントを変更・保存しないでください。',
+ modelFailure: '現在のモデル設定と添付の接続エラーを基に原因を分析し、確認手順を提案してください。認証情報の読み取りや表示、設定の変更や保存は行わないでください。',
+ documentFailure: 'ドキュメント「{title}」(ID: {id})の処理状況を確認し、添付エラーの原因と次の手順を説明してください。まだ再試行、再構築、変更は行わないでください。',
+ suggestFaqQuestions: '添付の標準質問と回答をもとに、この FAQ の類似質問を最大 {count} 件提案してください。意味を保ち、既存の質問、入力中の質問、反例との重複を避けてください。選択できる候補を示し、FAQ の保存や変更は行わないでください。',
+ mcpFailure: 'MCP サービス(ID: {id})を確認し、添付のツール取得または同期エラーの原因と確認手順を説明してください。認証情報の読み取りや表示、再接続、設定変更は行わないでください。',
+ syncFailure: 'データソース「{source}」(ID: {id})の同期ログ(ID: {log})を確認し、添付のエラー例と失敗件数から原因と対処方法を説明してください。同期の再試行やデータソースの変更は行わないでください。',
+ writeWikiRules: '現在のナレッジベースの用途に基づいて「{field}」の明確なルールを作成してください。用途が不明な場合は先に確認してください。対応する入力欄に記入し、システムの引用・出力規約を維持してください。保存や再解析は行わないでください。',
+ refineWikiRules: '添付の「{field}」のルールを、意味を保ちながら明確にしてください。対応する入力欄に記入し、システムの引用・出力規約を維持してください。保存や再解析は行わないでください。',
+ analyzeChunks: '添付の分割プレビューについて、原文とチャンクの抜粋、実行時のパラメータ、統計から、意味の分断や短すぎる・長すぎるチャンクを分析し、調整案を示してください。抜粋から確認できる問題と追加の原文が必要な判断を区別してください。設定変更やナレッジベースの再構築は行わないでください。',
+ },
askAboutAnswer: 'この回答について{name}に聞く',
selection: {
label: '選択中',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index a0b1f6e90..f47fd31e5 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -2620,6 +2620,76 @@ export default {
welcomeDesc: 'WeKnora 사용법을 안내하고, 워크스페이스의 문서 파싱, 지식 베이스 활동, Wiki 문제를 확인하고 처리하며, 에이전트를 만들고 설정할 수도 있습니다. 변경 전에 확인을 요청할지는 입력창 아래의 권한 수준에 따라 정해집니다.',
startFailed: '어시스턴트를 시작하지 못했습니다. 다시 시도해 주세요.',
askAboutDocument: '{name}에게 묻기',
+ chooseAction: "기능을 선택하거나 원하는 작업을 입력하세요.",
+ create: {
+ agentTitle: "자연어로 에이전트 만들기",
+ agentHint: "누구를 위해 어떤 일을 해야 하는지 설명하면 어시스턴트가 리소스를 선택하고 생성합니다.",
+ agentPlaceholder: "예: 제품 지식 베이스로 질문에 답하고 출처를 제시하며 정보가 없으면 알려주는 고객 지원 에이전트.",
+ automationTitle: "어시스턴트로 작업 만들기",
+ automationHint: "할 일과 실행 시간을 설명하면 어시스턴트가 자동화 작업으로 정리합니다.",
+ automationPlaceholder: "예: 매주 금요일 오후 5시에 제품 지식 베이스의 이번 주 업데이트를 요약해 주세요.",
+ requestLabel: "작업 설명",
+ manual: "직접 설정",
+ start: "어시스턴트에게 맡기기",
+ },
+ actions: {
+ writeAnswer: "답변 초안 작성",
+ refineAnswer: "답변 개선",
+ processSelected: "선택 항목 처리",
+ summarizeSelected: "핵심 요약",
+ compareDocuments: "문서 비교",
+ suggestTags: "태그 추천",
+ organizeDocuments: "폴더 정리",
+ summarizeActivity: "현재 {count}개 변경 내역 요약",
+ toolExamples: "사용 예시 보기",
+ readContent: "어시스턴트로 읽기",
+ readSummary: "핵심 내용 추출",
+ readSteps: "실행 단계 정리",
+ extractFaq: "FAQ 추출",
+ answerToDocument: "문서로 정리",
+ answerToFaq: "FAQ로 저장",
+ answerToAutomation: "예약 작업으로 만들기",
+ analyzeRun: "결과 분석",
+ summarizeRun: "이번 실행 요약",
+ compareRuns: "최근 실행 비교",
+ writePrompt: '작성 도움',
+ refinePrompt: '프롬프트 개선',
+ diagnose: '원인 분석',
+ suggestFaqQuestions: '유사 질문 제안',
+ refineRules: '규칙 개선',
+ analyzeChunks: '청크 결과 분석',
+ },
+ prompts: {
+ startAgentCreation: "자연어로 에이전트를 만들고 싶습니다. 먼저 누구를 위한 에이전트인지, 어떤 작업을 해야 하는지 물어봐 주세요. 요구 사항이 명확해지면 사용 가능한 모델, 지식 베이스, MCP 서비스와 스킬을 확인하고 적절한 리소스를 선택해 현재 권한 규칙에 따라 생성한 뒤 설정 화면을 열어 주세요.",
+ createAgent: "이 요청에 맞는 에이전트를 만드세요: {request}. 사용 가능한 모델, 지식 베이스, MCP, 스킬을 확인해 선택하세요. 꼭 필요한 누락 정보만 질문하고 현재 권한 정책을 따르며 생성 후 편집 화면을 열어 주세요.",
+ createAutomation: "예약 작업을 만드세요: {request}. 별도 지정이 없으면 시간대 {timezone}을 사용하세요. 독립적으로 실행 가능한 지침을 작성하고 일정을 검증해 다음 실행 시간을 보여 주세요. 실행 권한을 높이지 말고 현재 정책을 따르며 생성 후 작업을 열어 주세요.",
+ writeFaqAnswer: "표준 질문, 기존 답변, 확인 가능한 자료로 FAQ 답변을 작성하세요. 정보가 부족하면 질문하세요. 현재 답변 입력란에만 채우고 항목 추가, 저장, 기존 답변 변경은 하지 마세요.",
+ refineFaqAnswer: "FAQ 질문과 답변 초안 전체를 읽고 사실과 의미를 유지하며 명확성과 어조를 개선하세요. 현재 답변 입력란에만 반영하고 추가, 저장, 기존 답변 변경은 하지 마세요.",
+ summarizeDocuments: "지식 베이스 {kb}의 다음 문서만 읽으세요: {ids}. 핵심 내용, 공통 주제, 할 일을 문서 출처와 함께 요약하고 자료는 변경하지 마세요.",
+ compareDocuments: "지식 베이스 {kb}의 다음 문서만 비교하세요: {ids}. 적용 범위 차이를 고려해 공통점, 차이점, 상충하는 주장을 출처와 함께 보여 주고 변경하지 마세요.",
+ tagDocuments: "지식 베이스 {kb}의 문서 {ids}를 읽고 기존 태그를 우선해 문서별 태그와 이유를 제안하세요. 목록만 보여 주고 태그를 변경하지 마세요.",
+ organizeDocuments: "지식 베이스 {kb}의 문서 {ids}와 기존 폴더를 확인해 문서별 대상 위치와 이유를 제안하세요. 계획만 보여 주고 이동하거나 변경하지 마세요.",
+ summarizeActivity: "이 필터 스냅샷의 loaded_entry_ids만 요약하세요: {scope}. 같은 조건으로 조회하고 필요하면 페이지를 추가 조회하세요. 대상 자료, 작업자, 결과를 설명하고 감사 기록과 본문 변경을 구분하세요. 로드된 기록을 전체로 간주하지 마세요.",
+ explainMcpTools: "MCP 서비스 {id}의 저장된 도구 목록을 읽고 기능과 유용한 질문 예시 세 가지를 설명하세요. 오래되거나 불완전한 정보는 표시하고 새로고침, 도구 실행, 설정 변경은 하지 마세요.",
+ readSummary: "이 자료를 읽으세요: {source}. 출처와 함께 핵심, 결론, 한계를 추출하세요. 요약을 전체 본문으로 간주하거나 자료를 변경하지 마세요.",
+ readSteps: "이 자료를 읽고 근거가 있는 절차, 선행 조건, 확인 항목을 출처와 함께 정리하세요: {source}. 누락된 단계는 표시하고 사실을 만들거나 원문을 변경하지 마세요.",
+ extractFaq: "자료 {source}에서 근거 있는 질문과 답변을 항목별 출처와 함께 추출하세요. 선택할 FAQ 초안을 보여 주고 저장하거나 변경하지 마세요.",
+ answerToDocument: "이 답변과 원래 질문을 읽고 출처와 불확실성을 유지한 문서 초안을 작성하세요: {source}. 초안을 보여 주고 대상 지식 베이스를 확인한 뒤 현재 권한으로 생성하세요. 기존 자료는 덮어쓰지 마세요.",
+ answerToFaq: "이 답변과 원래 질문으로 표준 질문과 정확한 답변을 작성하세요: {source}. 초안을 보여 주고 대상 FAQ 지식 베이스를 확인하며 유사 항목을 검사한 뒤 현재 권한으로 저장하세요. 기존 항목은 덮어쓰지 마세요.",
+ answerToAutomation: "답변과 질문 {source}의 반복 작업을 독립 실행 가능한 예약 작업으로 정리하세요. 누락된 주기, 시간, 시간대를 질문하고 다음 실행을 검증해 보여 준 뒤 현재 권한으로 생성하세요. 실행 권한을 높이지 마세요.",
+ summarizeRun: "이 자동화 실행의 전체 기록과 답변을 읽으세요: {source}. 산출물, 발견 사항, 후속 작업을 요약하세요. 첨부 텍스트는 발췌입니다. 작업을 변경하거나 재실행하지 마세요.",
+ compareRuns: "자동화 실행 {source}를 같은 작업의 완료된 실행 {ids}와 비교하세요. 전체 답변을 읽고 입력과 실행 시점 차이를 고려해 결과 변화를 설명하세요. 작업을 변경하거나 재실행하지 마세요.",
+ writePrompt: '현재 에이전트의 목적과 설정에 맞는 시스템 프롬프트를 작성해 주세요. 목표가 불분명하면 먼저 질문해 주세요. 템플릿 자리 표시자를 유지하고 제안을 현재 편집기에 입력해 주세요. 저장된 에이전트를 변경하거나 저장하지 마세요.',
+ refinePrompt: '첨부한 시스템 프롬프트의 역할, 응답 요구사항, 도구 사용 규칙을 더 명확하게 개선해 주세요. 원래 의도와 템플릿 자리 표시자를 유지하고 수정 내용을 현재 편집기에 입력해 주세요. 저장된 에이전트를 변경하거나 저장하지 마세요.',
+ modelFailure: '현재 모델 설정과 첨부한 연결 오류를 바탕으로 실패 원인을 분석하고 점검 단계를 제안해 주세요. 인증 정보를 읽거나 표시하지 말고 설정을 변경하거나 저장하지 마세요.',
+ documentFailure: '문서 "{title}"(ID: {id})의 처리 상태를 확인하고 첨부 오류의 원인과 다음 단계를 제안해 주세요. 아직 재시도, 재구축 또는 문서 변경은 하지 마세요.',
+ suggestFaqQuestions: '첨부된 표준 질문과 답변을 바탕으로 현재 FAQ의 유사 질문을 최대 {count}개 제안해 주세요. 의미를 유지하고 기존 질문, 입력 중인 질문, 반례와 겹치지 않게 해 주세요. 선택할 수 있는 후보를 제시하고 FAQ를 저장하거나 수정하지 마세요.',
+ mcpFailure: 'MCP 서비스(ID: {id})를 확인하고 첨부된 도구 조회 또는 동기화 오류의 원인과 점검 절차를 설명해 주세요. 자격 증명을 읽거나 표시하지 말고 재연결이나 설정 변경도 하지 마세요.',
+ syncFailure: '데이터 소스 "{source}"(ID: {id})의 동기화 로그(ID: {log})를 확인하고 첨부된 오류 사례와 실패 건수로 원인과 해결 방법을 설명해 주세요. 동기화를 재시도하거나 데이터 소스를 수정하지 마세요.',
+ writeWikiRules: '현재 지식베이스의 용도에 맞게 "{field}"의 명확한 규칙을 작성해 주세요. 용도가 불분명하면 먼저 질문해 주세요. 해당 입력란에 작성하고 시스템의 인용 및 출력 규약을 유지해 주세요. 저장하거나 다시 파싱하지 마세요.',
+ refineWikiRules: '첨부된 "{field}" 규칙의 의미를 유지하면서 더 명확하게 개선해 주세요. 해당 입력란에 작성하고 시스템의 인용 및 출력 규약을 유지해 주세요. 저장하거나 다시 파싱하지 마세요.',
+ analyzeChunks: '첨부된 분할 미리보기의 원문과 청크 발췌, 실행 당시 매개변수, 통계를 바탕으로 의미 단절이나 지나치게 짧거나 긴 청크를 분석하고 조정안을 제안해 주세요. 발췌로 확인 가능한 문제와 추가 원문이 필요한 판단을 구분해 주세요. 설정 변경이나 지식베이스 재구축은 하지 마세요.',
+ },
askAboutAnswer: '이 답변에 대해 {name}에게 묻기',
selection: {
label: '선택됨',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index eb250e54b..2c14777af 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -2620,6 +2620,76 @@ export default {
welcomeDesc: 'Я отвечаю на вопросы о WeKnora, а также проверяю и обрабатываю разбор документов, активность баз знаний и проблемы Wiki в вашем пространстве, а также создаю и настраиваю агентов. Спрашивать ли подтверждение перед изменением, зависит от уровня доступа под полем ввода.',
startFailed: 'Не удалось запустить ассистента. Попробуйте ещё раз.',
askAboutDocument: 'Спросить: {name}',
+ chooseAction: "Выберите действие или опишите свою задачу.",
+ create: {
+ agentTitle: "Опишите своего агента",
+ agentHint: "Опишите пользователей и задачи. Помощник подберёт ресурсы и создаст агента.",
+ agentPlaceholder: "Например: агент поддержки, который отвечает по базе знаний о продукте, указывает источники и сообщает о недостающих данных.",
+ automationTitle: "Создать задачу с помощником",
+ automationHint: "Опишите, что и когда нужно выполнять. Помощник подготовит задачу автоматизации.",
+ automationPlaceholder: "Например: каждую пятницу в 17:00 подводить итоги обновлений базы знаний о продукте за неделю.",
+ requestLabel: "Описание задачи",
+ manual: "Настроить вручную",
+ start: "Продолжить с помощником",
+ },
+ actions: {
+ writeAnswer: "Составить ответ",
+ refineAnswer: "Улучшить ответ",
+ processSelected: "Обработать выбранное",
+ summarizeSelected: "Обобщить главное",
+ compareDocuments: "Сравнить документы",
+ suggestTags: "Предложить теги",
+ organizeDocuments: "Упорядочить папки",
+ summarizeActivity: "Обобщить эти обновления ({count})",
+ toolExamples: "Примеры использования",
+ readContent: "Читать с помощником",
+ readSummary: "Выделить главное",
+ readSteps: "Составить инструкцию",
+ extractFaq: "Составить FAQ",
+ answerToDocument: "Создать документ",
+ answerToFaq: "Сохранить как FAQ",
+ answerToAutomation: "Создать задание по расписанию",
+ analyzeRun: "Разобрать результат",
+ summarizeRun: "Итоги этого запуска",
+ compareRuns: "Сравнить последние запуски",
+ writePrompt: 'Помочь написать',
+ refinePrompt: 'Улучшить промпт',
+ diagnose: 'Разобрать ошибку',
+ suggestFaqQuestions: 'Предложить варианты',
+ refineRules: 'Улучшить правила',
+ analyzeChunks: 'Анализ разбиения',
+ },
+ prompts: {
+ startAgentCreation: "Я хочу создать агента на естественном языке. Сначала спросите, для кого он предназначен и какие задачи должен выполнять. Когда требования станут понятны, проверьте доступные модели, базы знаний, сервисы MCP и навыки, выберите подходящие ресурсы, создайте агента с соблюдением текущих правил доступа и откройте его настройки.",
+ createAgent: "Создайте агента по запросу: {request}. Проверьте доступные модели, базы знаний, MCP и навыки, подберите ресурсы. Уточняйте только необходимые данные, соблюдайте текущие права и откройте редактор после создания.",
+ createAutomation: "Создайте задание по расписанию: {request}. Если не указано иное, используйте часовой пояс {timezone}. Подготовьте самостоятельную инструкцию, проверьте расписание и покажите следующие запуски. Не повышайте права исполнения, соблюдайте текущую политику и откройте созданное задание.",
+ writeFaqAnswer: "Подготовьте ответ FAQ по вопросу, существующим ответам и проверяемым источникам. Уточните недостающие факты. Заполните только текущее поле ответа, не добавляя, не сохраняя и не меняя существующие ответы.",
+ refineFaqAnswer: "Прочитайте вопрос FAQ и полный черновик ответа. Улучшите ясность и тон, сохранив факты и смысл. Заполните только текущее поле, не добавляя, не сохраняя и не меняя существующие ответы.",
+ summarizeDocuments: "Прочитайте только эти документы базы {kb}: {ids}. Обобщите главное, общие темы и задачи с указанием источников. Ничего не изменяйте.",
+ compareDocuments: "Сравните только документы базы {kb}: {ids}. Покажите сходства, различия и противоречия с источниками, учитывая область применимости. Ничего не изменяйте.",
+ tagDocuments: "Прочитайте документы базы {kb}: {ids}. Предложите теги для каждого с обоснованием, предпочитая существующие. Покажите список без изменения тегов.",
+ organizeDocuments: "Изучите документы {ids} и папки базы {kb}. Предложите расположение и причину для каждого документа. Покажите план без перемещения и изменений.",
+ summarizeActivity: "Обобщите только loaded_entry_ids этого снимка фильтров: {scope}. Запрашивайте с теми же фильтрами, при необходимости постранично. Укажите ресурсы, исполнителей и результаты. Отличайте события журнала от изменений содержимого; загруженные записи не являются всей историей.",
+ explainMcpTools: "Прочитайте сохранённый каталог инструментов MCP {id}. Объясните возможности и приведите три запроса-примера, отметив устаревшие или неполные данные. Не обновляйте каталог, не вызывайте инструменты и не меняйте настройки.",
+ readSummary: "Прочитайте источник: {source}. Выделите главное, выводы и ограничения с ссылками. Не принимайте краткое содержание за полный текст и не изменяйте источник.",
+ readSteps: "Прочитайте источник: {source}. Выделите подтверждённые шаги, условия и проверки с ссылками. Отметьте пробелы, не выдумывая факты и не меняя оригинал.",
+ extractFaq: "Извлеките из источника {source} обоснованные вопросы и ответы с ссылками для каждого. Покажите черновики FAQ для выбора, ничего не сохраняя и не меняя.",
+ answerToDocument: "Прочитайте ответ и вопрос: {source}. Подготовьте документ с сохранением ссылок и неопределённостей. Покажите черновик, уточните целевую базу и создайте документ по текущим правилам, не перезаписывая существующие материалы.",
+ answerToFaq: "По ответу и вопросу {source} составьте стандартный вопрос и точный ответ. Покажите черновик, уточните базу FAQ, проверьте похожие записи и сохраните по текущим правилам без перезаписи.",
+ answerToAutomation: "По ответу и вопросу {source} оформите повторяемую работу как самостоятельное задание. Уточните частоту, время и часовой пояс, проверьте и покажите ближайшие запуски, затем создайте по текущим правилам без повышения прав.",
+ summarizeRun: "Прочитайте полную запись и ответ запуска: {source}. Обобщите результаты, выводы и дальнейшие действия; приложен лишь фрагмент. Не меняйте и не запускайте задание повторно.",
+ compareRuns: "Сравните запуск {source} с завершёнными запусками той же задачи: {ids}. Прочитайте полные ответы и объясните изменения с учётом входных данных и времени. Не меняйте и не запускайте задание повторно.",
+ writePrompt: 'Помоги составить системный промпт с учётом назначения и настроек текущего агента. Если цель неясна, сначала задай вопросы. Вставь предложение в текущий редактор, сохранив переменные шаблона. Не сохраняй и не изменяй сохранённого агента.',
+ refinePrompt: 'Улучши приложенный системный промпт: уточни обязанности, требования к ответам и правила использования инструментов. Сохрани исходный смысл и переменные шаблона. Вставь исправления в текущий редактор, не сохраняя и не изменяя сохранённого агента.',
+ modelFailure: 'Проанализируй приложенную ошибку подключения с учётом текущих настроек модели и предложи шаги проверки. Не читай и не показывай секретные данные, не изменяй и не сохраняй настройки.',
+ documentFailure: 'Проверь обработку документа «{title}» (ID: {id}), объясни приложенную ошибку и предложи следующие шаги. Пока не запускай повторную обработку, не перестраивай и не изменяй документ.',
+ suggestFaqQuestions: 'Предложите до {count} похожих вопросов для этого FAQ на основе приложенного основного вопроса и ответов. Сохраните смысл, избегайте существующих вариантов, текущего черновика и отрицательных примеров. Покажите варианты для выбора, не сохраняйте и не изменяйте FAQ.',
+ mcpFailure: 'Проверьте сервис MCP (ID: {id}) и объясните причину приложенной ошибки получения или синхронизации инструментов. Предложите шаги диагностики без чтения или раскрытия ключей, повторного подключения и изменения настроек.',
+ syncFailure: 'Проверьте журнал синхронизации {log} источника «{source}» (ID: {id}). Объясните причину по приложенным примерам ошибок и числу сбоев, предложите дальнейшие действия. Не повторяйте синхронизацию и не изменяйте источник.',
+ writeWikiRules: 'Составьте понятные правила для поля «{field}» с учётом назначения текущей базы знаний. Если назначение неясно, сначала спросите меня. Заполните соответствующее поле редактора, сохранив системные правила цитирования и формата вывода. Не сохраняйте и не запускайте повторный разбор.',
+ refineWikiRules: 'Уточните приложенные правила поля «{field}», сохранив их смысл. Заполните соответствующее поле редактора, сохранив системные правила цитирования и формата вывода. Не сохраняйте и не запускайте повторный разбор.',
+ analyzeChunks: 'Проанализируйте приложенный результат разбиения по отрывкам исходного текста и фрагментов, параметрам этого запуска и статистике. Найдите разрывы смысла, слишком короткие или длинные фрагменты и предложите настройки. Отделите выводы по отрывкам от тех, которым нужен дополнительный исходный текст. Не изменяйте настройки и не перестраивайте базу знаний.',
+ },
askAboutAnswer: 'Спросить {name} об этом ответе',
selection: {
label: 'Выделено',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 617d30f2a..22a6b289c 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -2622,6 +2622,76 @@ export default {
welcomeDesc: '我可以解答 WeKnora 的用法,也可以查看和处理你空间里的文档解析、知识库动态和 Wiki 问题,还能帮你创建和配置智能体。改动前是否先请你确认,由输入框下方的权限等级决定。',
startFailed: '启动助手失败,请重试',
askAboutDocument: '问 {name}',
+ chooseAction: "选择一个功能,或直接输入你的需求。",
+ create: {
+ agentTitle: "用自然语言创建智能体",
+ agentHint: "说说它为谁服务、需要完成什么,助手会帮你选择资源并创建。",
+ agentPlaceholder: "例如:创建一个产品客服助手,根据产品知识库回答使用问题,回答附上来源,找不到答案时说明原因。",
+ automationTitle: "用助手创建任务",
+ automationHint: "描述要做什么、何时运行,助手会帮你整理成自动化任务。",
+ automationPlaceholder: "例如:每周五下午 5 点汇总产品知识库本周的更新,列出新增文档和重点变化。",
+ requestLabel: "任务描述",
+ manual: "手动配置",
+ start: "交给助手",
+ },
+ actions: {
+ writeAnswer: "起草答案",
+ refineAnswer: "优化答案",
+ processSelected: "处理所选",
+ summarizeSelected: "汇总要点",
+ compareDocuments: "比较差异",
+ suggestTags: "推荐标签",
+ organizeDocuments: "整理目录",
+ summarizeActivity: "汇总这 {count} 条动态",
+ toolExamples: "查看使用示例",
+ readContent: "用助手阅读",
+ readSummary: "提炼要点",
+ readSteps: "整理操作步骤",
+ extractFaq: "提取 FAQ",
+ answerToDocument: "整理为文档",
+ answerToFaq: "保存为 FAQ",
+ answerToAutomation: "设为定时任务",
+ analyzeRun: "分析结果",
+ summarizeRun: "总结这次",
+ compareRuns: "对比最近几次",
+ writePrompt: '帮我写',
+ refinePrompt: '优化提示词',
+ diagnose: '分析原因',
+ suggestFaqQuestions: '补充问法',
+ refineRules: '优化规则',
+ analyzeChunks: '分析分块效果',
+ },
+ prompts: {
+ startAgentCreation: "我想用自然语言创建智能体。请先问我它为谁服务、要完成什么任务。需求明确后,检查可用模型、知识库、MCP 和技能,选择合适的资源,遵循当前权限规则创建并打开配置页。",
+ createAgent: "请根据我的需求创建智能体:{request}。先检查当前可用的模型、知识库、MCP 和技能,选择合适的资源;只询问必要的缺失信息,遵循当前权限规则,创建成功后打开编辑页。",
+ createAutomation: "请创建定时任务:{request}。未另行指定时使用时区 {timezone}。把说明写成可独立执行的完整任务,先校验时间并展示后续运行时刻,遵循当前权限规则,不提高执行权限;创建后打开任务。",
+ writeFaqAnswer: "请根据标准问、已有答案及可核实的资料起草 FAQ 答案,信息不足先询问,不要编造。将草稿填入当前答案输入框,不添加条目、不保存或改动已有答案。",
+ refineFaqAnswer: "请读取当前 FAQ 标准问和完整答案草稿,保留事实与原意,优化清晰度和语气。只回填当前答案输入框,不添加条目、不保存或改动已有答案。",
+ summarizeDocuments: "请只读取知识库 {kb} 中这些文档:{ids}。汇总重点、共同主题与待办,注明各结论的文档来源;不要修改资料。",
+ compareDocuments: "请只比较知识库 {kb} 中这些文档:{ids}。列出共同点、差异和相互矛盾的说法,引用来源,不把不同适用范围误当冲突;不要修改资料。",
+ tagDocuments: "请读取知识库 {kb} 中这些文档:{ids},优先使用现有标签,逐份给出标签建议和理由。先展示建议清单,不改动标签。",
+ organizeDocuments: "请读取知识库 {kb} 中这些文档:{ids} 及现有目录,按内容提出目录整理方案,逐份列出目标位置与理由。先展示方案,不移动或修改文档。",
+ summarizeActivity: "请仅汇总这个筛选快照中 loaded_entry_ids 指定的动态:{scope}。按筛选条件查询并翻页补齐,说明涉及资料、操作人与结果。区分操作日志与正文改动,不把已加载记录当成全部动态。",
+ explainMcpTools: "请读取 MCP 服务 {id} 的缓存工具目录,说明它能做什么,给出三个实用提问示例,并注明目录是否陈旧或不完整。不要刷新目录、调用工具或修改配置。",
+ readSummary: "请读取这份资料:{source}。提炼重点、关键结论与限制,保留出处,不把摘要当完整原文,也不要改动资料。",
+ readSteps: "请读取这份资料:{source},整理其中有依据的操作步骤、前提和检查点,附上出处。缺失步骤明确说明,不补造事实,也不要改动原文。",
+ extractFaq: "请读取这份资料:{source},提取有原文依据的常见问题与答案,逐条注明来源,先展示 FAQ 草稿供我选择,不保存或修改资料。",
+ answerToDocument: "请读取这条回答及原问题:{source},整理成结构清晰的文档,保留来源与不确定性。先展示草稿并让我选择目标知识库,再按当前权限规则创建文档,不覆盖现有资料。",
+ answerToFaq: "请读取这条回答及原问题:{source},整理出标准问和准确答案。先展示草稿并让我选择目标 FAQ 知识库,检查相近条目后按当前权限规则保存,不覆盖已有条目。",
+ answerToAutomation: "请读取这条回答及原问题:{source},把需要重复完成的工作整理成可独立执行的定时任务。向我确认缺失的频率、时间和时区,校验并展示后续运行时刻,再按当前权限规则创建,不提高执行权限。",
+ summarizeRun: "请读取这次自动化运行的完整记录与回答:{source}。总结产出、重要发现和待办,附带文本只是摘录;不要修改或重跑任务。",
+ compareRuns: "请读取这次自动化运行 {source},并与同一任务的这些已完成运行比较:{ids}。读取完整回答,比较结果变化,区分输入或执行时间不同造成的差异;不要修改或重跑任务。",
+ writePrompt: '请结合当前智能体的用途和配置,帮我起草系统提示词。如果目标还不明确,先询问我。将建议填入当前编辑器,保留模板占位符,不要保存或修改已保存的智能体。',
+ refinePrompt: '请优化我附带的系统提示词,使职责、回答要求和工具使用规则更清晰,保留原意及模板占位符。将修改填入当前编辑器,不要保存或修改已保存的智能体。',
+ modelFailure: '请结合当前模型配置和附带的连接错误,分析失败原因并给出排查步骤。不要读取或展示密钥,也不要修改或保存配置。',
+ documentFailure: '请检查文档「{title}」(ID:{id})的处理情况,结合附带的错误说明原因并建议下一步。先不要重试、重建或修改文档。',
+ suggestFaqQuestions: '请根据附带的标准问题和答案,为当前 FAQ 建议最多 {count} 条相似问法。保留原意,避免已有问法、正在输入的问法及反例。先给出候选供我选择,不要保存或修改现有 FAQ。',
+ mcpFailure: '请结合附带的工具获取或同步错误,检查 MCP 服务(ID:{id})并分析原因,给出排查步骤。不要读取或展示密钥,也不要重连或修改配置。',
+ syncFailure: '请检查数据源「{source}」(ID:{id})的同步记录(ID:{log}),结合附带的错误样例和失败数量分析原因。先给出处理建议,不要重试同步或修改数据源。',
+ writeWikiRules: '请根据当前知识库的用途,为「{field}」起草清晰的规则。如果用途还不明确,先询问我。将建议填入对应输入框,保留系统固定的引用与输出协议,不要保存或重新解析。',
+ refineWikiRules: '请优化附带的「{field}」规则,让表达更明确并保留原意。将修改填入对应输入框,保留系统固定的引用与输出协议,不要保存或重新解析。',
+ analyzeChunks: '请分析附带的这次分块预览,结合原文与分块摘录、当次参数和统计,说明是否存在割裂语义、过短或过长的分块,并给出参数调整建议。区分摘录可验证的问题与需要更多原文的判断,不要修改配置或重建知识库。',
+ },
askAboutAnswer: '就这条回答问 {name}',
selection: {
label: '已选中',
diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts
index 0838485ef..524fe1052 100644
--- a/frontend/src/i18n/locales/zh-TW.ts
+++ b/frontend/src/i18n/locales/zh-TW.ts
@@ -2622,6 +2622,76 @@ export default {
welcomeDesc: '我可以解答 WeKnora 的用法,也可以檢視和處理你空間裡的文件解析、知識庫動態和 Wiki 問題,還能幫你建立和設定智慧代理。變更前是否先請你確認,由輸入框下方的權限等級決定。',
startFailed: '啟動助手失敗,請重試',
askAboutDocument: '問 {name}',
+ chooseAction: "選擇一項功能,或直接輸入你的需求。",
+ create: {
+ agentTitle: "用自然語言建立智慧體",
+ agentHint: "說說它為誰服務、需要完成什麼,助手會協助選擇資源並建立。",
+ agentPlaceholder: "例如:建立產品客服智慧體,根據產品知識庫回答使用問題,附上來源,找不到答案時說明原因。",
+ automationTitle: "用助手建立任務",
+ automationHint: "描述要做什麼、何時執行,助手會幫你整理成自動化任務。",
+ automationPlaceholder: "例如:每週五下午 5 點彙整產品知識庫本週更新,列出新增文件與重點變化。",
+ requestLabel: "任務描述",
+ manual: "手動設定",
+ start: "交給助手",
+ },
+ actions: {
+ writeAnswer: "起草答案",
+ refineAnswer: "最佳化答案",
+ processSelected: "處理所選",
+ summarizeSelected: "彙整重點",
+ compareDocuments: "比較差異",
+ suggestTags: "推薦標籤",
+ organizeDocuments: "整理目錄",
+ summarizeActivity: "彙整這 {count} 筆動態",
+ toolExamples: "查看使用範例",
+ readContent: "用助手閱讀",
+ readSummary: "提煉重點",
+ readSteps: "整理操作步驟",
+ extractFaq: "擷取 FAQ",
+ answerToDocument: "整理為文件",
+ answerToFaq: "儲存為 FAQ",
+ answerToAutomation: "設為排程任務",
+ analyzeRun: "分析結果",
+ summarizeRun: "總結這次",
+ compareRuns: "比較最近幾次",
+ writePrompt: '幫我寫',
+ refinePrompt: '改善提示詞',
+ diagnose: '分析原因',
+ suggestFaqQuestions: '補充問法',
+ refineRules: '最佳化規則',
+ analyzeChunks: '分析分塊效果',
+ },
+ prompts: {
+ startAgentCreation: "我想用自然語言建立智慧體。請先問我它為誰服務、要完成什麼任務。需求明確後,檢查可用模型、知識庫、MCP 和技能,選擇合適的資源,遵循目前權限規則建立並開啟設定頁面。",
+ createAgent: "請依需求建立智慧體:{request}。先檢查目前可用的模型、知識庫、MCP 與技能,選擇適合的資源;只詢問必要的缺漏資訊,遵循目前權限規則,建立後開啟編輯頁。",
+ createAutomation: "請建立排程任務:{request}。未另行指定時使用時區 {timezone}。將說明寫成可獨立執行的完整任務,先驗證時間並顯示後續執行時刻,遵循目前權限規則,不提高執行權限;建立後開啟任務。",
+ writeFaqAnswer: "請根據標準問、已有答案與可查證資料起草 FAQ 答案,資訊不足先詢問,不要編造。將草稿填入目前答案欄位,不新增項目、不儲存或修改已有答案。",
+ refineFaqAnswer: "請讀取目前 FAQ 標準問與完整答案草稿,保留事實及原意,改善清晰度與語氣。只回填目前答案欄位,不新增項目、不儲存或修改已有答案。",
+ summarizeDocuments: "請只讀取知識庫 {kb} 中這些文件:{ids}。彙整重點、共同主題與待辦,標明各結論的文件來源;不要修改資料。",
+ compareDocuments: "請只比較知識庫 {kb} 中這些文件:{ids}。列出共通點、差異與矛盾說法並引用來源,區分適用範圍差異;不要修改資料。",
+ tagDocuments: "請讀取知識庫 {kb} 中這些文件:{ids},優先使用現有標籤,逐份提出標籤建議與理由。先顯示清單,不修改標籤。",
+ organizeDocuments: "請讀取知識庫 {kb} 中這些文件:{ids} 與現有目錄,依內容提出整理方案,逐份列出目標位置與理由。先顯示方案,不移動或修改文件。",
+ summarizeActivity: "請只彙整此篩選快照中 loaded_entry_ids 指定的動態:{scope}。依篩選條件查詢並翻頁補齊,說明相關資料、操作者與結果。區分操作紀錄與內文修改,勿將已載入紀錄視為全部動態。",
+ explainMcpTools: "請讀取 MCP 服務 {id} 的快取工具目錄,說明功能,提供三個實用提問範例,註明目錄是否過時或不完整。不要重新整理、呼叫工具或修改設定。",
+ readSummary: "請讀取這份資料:{source}。提煉重點、結論與限制並保留出處,不將摘要視為完整內文,也不要修改資料。",
+ readSteps: "請讀取這份資料:{source},整理有依據的操作步驟、前提與檢查點並附出處。明確說明缺漏,不編造事實,也不要修改原文。",
+ extractFaq: "請讀取這份資料:{source},擷取有原文依據的常見問題與答案,逐條註明來源,先顯示 FAQ 草稿供選擇,不儲存或修改資料。",
+ answerToDocument: "請讀取這則回答與原問題:{source},整理成清晰文件並保留來源及不確定性。先顯示草稿並讓我選擇目標知識庫,再依目前權限建立文件,不覆寫既有資料。",
+ answerToFaq: "請讀取這則回答與原問題:{source},整理標準問與正確答案。先顯示草稿並讓我選擇目標 FAQ 知識庫,檢查相近項目後依目前權限儲存,不覆寫既有項目。",
+ answerToAutomation: "請讀取這則回答與原問題:{source},將重複工作整理成可獨立執行的排程任務。確認缺漏的頻率、時間與時區,驗證並顯示後續執行時刻,再依目前權限建立,不提高執行權限。",
+ summarizeRun: "請讀取這次自動化執行的完整紀錄與回答:{source}。總結產出、重要發現與待辦,附帶文字只是摘錄;不要修改或重跑任務。",
+ compareRuns: "請讀取這次自動化執行 {source},與同一任務的這些已完成執行比較:{ids}。讀取完整回答,區分輸入或執行時間不同造成的差異;不要修改或重跑任務。",
+ writePrompt: '請根據目前智慧代理的用途和設定,幫我草擬系統提示詞。如果目標還不明確,先詢問我。將建議填入目前編輯器,保留範本預留位置,不要儲存或修改已儲存的智慧代理。',
+ refinePrompt: '請改善我附帶的系統提示詞,讓職責、回答要求和工具使用規則更清楚,保留原意及範本預留位置。將修改填入目前編輯器,不要儲存或修改已儲存的智慧代理。',
+ modelFailure: '請根據目前模型設定和附帶的連線錯誤,分析失敗原因並提供排查步驟。不要讀取或顯示金鑰,也不要修改或儲存設定。',
+ documentFailure: '請檢查文件「{title}」(ID:{id})的處理情況,根據附帶的錯誤說明原因並建議下一步。先不要重試、重建或修改文件。',
+ suggestFaqQuestions: '請根據附帶的標準問題與答案,為目前 FAQ 建議最多 {count} 條相似問法。保留原意,避免已有問法、正在輸入的問法及反例。先提供候選供我選擇,不要儲存或修改現有 FAQ。',
+ mcpFailure: '請根據附帶的工具取得或同步錯誤,檢查 MCP 服務(ID:{id})並分析原因,提供排查步驟。不要讀取或顯示金鑰,也不要重新連線或修改設定。',
+ syncFailure: '請檢查資料來源「{source}」(ID:{id})的同步記錄(ID:{log}),根據附帶的錯誤範例與失敗數量分析原因。先提供處理建議,不要重試同步或修改資料來源。',
+ writeWikiRules: '請根據目前知識庫的用途,為「{field}」起草清楚的規則。如果用途尚不明確,先詢問我。將建議填入對應輸入框,保留系統固定的引用與輸出協定,不要儲存或重新解析。',
+ refineWikiRules: '請最佳化附帶的「{field}」規則,讓表達更明確並保留原意。將修改填入對應輸入框,保留系統固定的引用與輸出協定,不要儲存或重新解析。',
+ analyzeChunks: '請分析附帶的這次分塊預覽,根據原文與分塊摘錄、當次參數和統計,說明是否有語意割裂、過短或過長的分塊,並提供參數調整建議。區分摘錄可驗證的問題與需要更多原文的判斷,不要修改設定或重建知識庫。',
+ },
askAboutAnswer: '就這則回答問 {name}',
selection: {
label: '已選取',
diff --git a/frontend/src/stores/assistant.ts b/frontend/src/stores/assistant.ts
index 8d966cd16..f9608d261 100644
--- a/frontend/src/stores/assistant.ts
+++ b/frontend/src/stores/assistant.ts
@@ -97,6 +97,13 @@ export interface AssistantOpenRequest {
focus?: Pick<AssistantPageContext, 'wikiIssueIds'>
}
+export interface AssistantContextAction {
+ key: string
+ label: string
+ query: string
+ disabled?: boolean
+}
+
const SESSION_KEY_PREFIX = 'weknora:assistant-session'
const VISIBLE_KEY_PREFIX = 'weknora:assistant-visible'
const MODEL_KEY_PREFIX = 'weknora:assistant-model'
@@ -187,6 +194,8 @@ export const useAssistantStore = defineStore('assistant', () => {
const visible = ref(false)
const sessionId = ref('')
const pendingRequest = ref<AssistantOpenRequest | null>(null)
+ const actionSuggestions = shallowRef<{ label: string; actions: AssistantContextAction[] } | null>(null)
+ const clearActionSuggestions = () => { actionSuggestions.value = null }
// Publishers in mount order, so a nested page (Wiki) refines its parent (KB).
const layers = shallowReactive(new Map<symbol, Partial<AssistantPageContext>>())
const dismissedKey = ref('')
@@ -228,11 +237,14 @@ export const useAssistantStore = defineStore('assistant', () => {
})
// Whether the assistant may read and fill the page beside it.
const pageAccess = ref(true)
+ // Suggestions belong to the page or dialog from which the assistant was opened.
+ watch([attachKey, pageAccess], clearActionSuggestions, { flush: 'sync' })
const effectiveAccessLevel = computed(() => capAssistantAccessLevel(accessLevel.value, accessCeiling.value))
/** The workspace's name for the assistant; empty means the default. */
const displayName = computed(() => workspaceConfig.value?.display_name?.trim() || '')
const restore = () => {
+ clearActionSuggestions()
try {
sessionId.value = sessionStorage.getItem(storageKey(SESSION_KEY_PREFIX)) || ''
visible.value = sessionStorage.getItem(storageKey(VISIBLE_KEY_PREFIX)) === '1'
@@ -286,6 +298,7 @@ export const useAssistantStore = defineStore('assistant', () => {
}
}
const setSession = (id: string) => {
+ clearActionSuggestions()
sessionId.value = id
try {
if (id) sessionStorage.setItem(storageKey(SESSION_KEY_PREFIX), id)
@@ -387,12 +400,14 @@ export const useAssistantStore = defineStore('assistant', () => {
let queuedSeq = 0
/** Asks in the open conversation, or starts one when there is none. */
const ask = (query: string) => {
+ clearActionSuggestions()
if (!sessionId.value) {
open({ query })
+ focusComposer()
return
}
queuedMessage.value = { id: ++queuedSeq, query }
- setVisible(true)
+ focusComposer()
}
const takeQueuedMessage = () => {
const message = queuedMessage.value
@@ -406,6 +421,17 @@ export const useAssistantStore = defineStore('assistant', () => {
focusRequest.value++
}
+ const showActionSuggestions = (suggestions: { label: string; actions: AssistantContextAction[] }) => {
+ if (!pageAccess.value) return
+ actionSuggestions.value = suggestions
+ focusComposer()
+ }
+ const askSuggestedAction = (key: string) => {
+ const action = actionSuggestions.value?.actions.find(item => item.key === key)
+ if (!action || action.disabled || !pageAccess.value) return
+ ask(action.query)
+ }
+
const pageDraft = ref<AssistantPageDraft | null>(null)
const setPageDraft = (draft: AssistantPageDraft | null) => {
pageDraft.value = draft
@@ -427,6 +453,7 @@ export const useAssistantStore = defineStore('assistant', () => {
layers.delete(owner)
}
const dismissPageContext = () => {
+ clearActionSuggestions()
dismissedKey.value = attachKey.value
}
const restorePageContext = () => {
@@ -447,6 +474,10 @@ export const useAssistantStore = defineStore('assistant', () => {
layout,
width,
pendingRequest,
+ actionSuggestions,
+ showActionSuggestions,
+ askSuggestedAction,
+ clearActionSuggestions,
pageContext,
contextAttached,
pageTitle,
diff --git a/frontend/src/views/agent/AgentEditorModal.vue b/frontend/src/views/agent/AgentEditorModal.vue
index 60b24a181..c9d0f2ab7 100644
--- a/frontend/src/views/agent/AgentEditorModal.vue
+++ b/frontend/src/views/agent/AgentEditorModal.vue
@@ -198,19 +198,27 @@
</div>
<div class="setting-control setting-control-full" style="position: relative;">
<!-- Agent模式:统一提示词(使用 {{web_search_status}} 占位符动态控制行为) -->
- <div v-if="isAgentMode" class="textarea-with-template">
+ <div v-if="isAgentMode" class="textarea-with-template textarea-with-assistant">
<t-textarea ref="promptTextareaRef" v-model="formData.config.system_prompt"
:placeholder="systemPromptPlaceholder" :autosize="{ minRows: 10, maxRows: 25 }"
@input="handlePromptInput" class="system-prompt-textarea" />
+ <AssistantActionButton class="prompt-assistant-action"
+ :label="$t(formData.config.system_prompt?.trim() ? 'assistant.actions.refinePrompt' : 'assistant.actions.writePrompt')"
+ :query="$t(formData.config.system_prompt?.trim() ? 'assistant.prompts.refinePrompt' : 'assistant.prompts.writePrompt')"
+ :selection="{ field: $t('agent.editor.systemPrompt'), text: formData.config.system_prompt || '' }" />
<PromptTemplateSelector type="agentSystemPrompt" position="corner"
:hasKnowledgeBase="hasKnowledgeBase" @select="handleSystemPromptTemplateSelect"
@reset-default="handleAgentSystemPromptResetDefault" />
</div>
<!-- 普通模式:单个提示词 -->
- <div v-else class="textarea-with-template">
+ <div v-else class="textarea-with-template textarea-with-assistant">
<t-textarea ref="promptTextareaRef" v-model="formData.config.system_prompt"
:placeholder="systemPromptPlaceholder" :autosize="{ minRows: 10, maxRows: 25 }"
@input="handlePromptInput" class="system-prompt-textarea" />
+ <AssistantActionButton class="prompt-assistant-action"
+ :label="$t(formData.config.system_prompt?.trim() ? 'assistant.actions.refinePrompt' : 'assistant.actions.writePrompt')"
+ :query="$t(formData.config.system_prompt?.trim() ? 'assistant.prompts.refinePrompt' : 'assistant.prompts.writePrompt')"
+ :selection="{ field: $t('agent.editor.systemPrompt'), text: formData.config.system_prompt || '' }" />
<PromptTemplateSelector type="systemPrompt" position="corner"
:hasKnowledgeBase="hasKnowledgeBase" @select="handleSystemPromptTemplateSelect"
@reset-default="handleSystemPromptTemplateSelect" />
@@ -1879,6 +1887,7 @@ import { MessagePlugin } from 'tdesign-vue-next';
import { useModalShell } from '@/composables/useModalShell'
import { useAssistantPageContext } from '@/composables/useAssistantPageContext'
import SettingsModalShell from '@/components/SettingsModalShell.vue'
+import AssistantActionButton from '@/components/assistant/AssistantActionButton.vue'
import {
createAgent,
updateAgent,
@@ -6394,6 +6403,18 @@ const handleSave = async () => {
width: 100%;
}
+.textarea-with-assistant {
+ .prompt-assistant-action {
+ position: absolute;
+ left: 8px;
+ bottom: 8px;
+ }
+
+ :deep(.t-textarea__inner) {
+ padding-bottom: 44px;
+ }
+}
+
.intent-prompts-editor {
width: 100%;
display: flex;
diff --git a/frontend/src/views/agent/AgentList.test.ts b/frontend/src/views/agent/AgentList.test.ts
index 521f82dda..7d864e886 100644
--- a/frontend/src/views/agent/AgentList.test.ts
+++ b/frontend/src/views/agent/AgentList.test.ts
@@ -27,7 +27,7 @@ function setup(t: TestContext) {
'@/composables/useResourcePins': { useResourcePins: () => ({ favorites: vue.ref([]), recents: vue.ref([]) }) },
'@/composables/useAssistantPageContext': { useAssistantPageContext() {} },
'@/api/agent': {}, '@/api/chat/index': {}, '@/api/organization': {},
- '@/config/contextualGuides': {}, '@/config/settingsRoute': {},
+ '@/config/contextualGuides': { markContextualGuideDone() {} }, '@/config/settingsRoute': {},
'@/utils/resourceListSearch': {}, '@/utils/card-list-badge': {}, '@/utils/resourceSorting': sorting,
})
return { ...f, ...page, fetchAgentsForList }
@@ -53,3 +53,16 @@ test('refreshes the mounted agent list once per burst, ignoring other areas and
t.mock.timers.tick(300)
assert.equal(f.fetchAgentsForList.mock.callCount(), 1)
})
+
+test('the original create entry opens the configuration form directly', async t => {
+ const f = setup(t)
+ await flush()
+ f.vm.editingAgent = { id: 'previous-agent' }
+ f.vm.editorMode = 'edit'
+ f.vm.editorInitialSection = 'knowledge'
+ f.vm.handleCreateAgent()
+ assert.equal(f.vm.editorVisible, true)
+ assert.equal(f.vm.editorMode, 'create')
+ assert.equal(f.vm.editorInitialSection, 'basic')
+ assert.equal(f.vm.editingAgent, null)
+})
diff --git a/frontend/src/views/agent/AgentList.vue b/frontend/src/views/agent/AgentList.vue
index dfac1055b..eb54d2b68 100644
--- a/frontend/src/views/agent/AgentList.vue
+++ b/frontend/src/views/agent/AgentList.vue
@@ -15,27 +15,13 @@
<t-button variant="text" theme="default" size="small" class="header-action-btn"
data-guide="agent-list-create" style="--wails-draggable: no-drag" @click="handleCreateAgent">
<template #icon>
- <span class="btn-icon-wrapper">
- <svg class="sparkles-icon" width="19" height="19" viewBox="0 0 20 20" fill="none"
- xmlns="http://www.w3.org/2000/svg">
- <path
- d="M10 3L10.8 6.2C10.9 6.7 11.3 7.1 11.8 7.2L15 8L11.8 8.8C11.3 8.9 10.9 9.3 10.8 9.8L10 13L9.2 9.8C9.1 9.3 8.7 8.9 8.2 8.8L5 8L8.2 7.2C8.7 7.1 9.1 6.7 9.2 6.2L10 3Z"
- fill="currentColor" stroke="currentColor" stroke-width="0.8" stroke-linecap="round"
- stroke-linejoin="round" />
- <path
- d="M15.5 4L15.8 5.2C15.85 5.45 16.05 5.65 16.3 5.7L17.5 6L16.3 6.3C16.05 6.35 15.85 6.55 15.8 6.8L15.5 8L15.2 6.8C15.15 6.55 14.95 6.35 14.7 6.3L13.5 6L14.7 5.7C14.95 5.65 15.15 5.45 15.2 5.2L15.5 4Z"
- fill="currentColor" stroke="currentColor" stroke-width="0.6" stroke-linecap="round"
- stroke-linejoin="round" />
- <path
- d="M4.5 13L4.8 14.2C4.85 14.45 5.05 14.65 5.3 14.7L6.5 15L5.3 15.3C5.05 15.35 4.85 15.55 4.8 15.8L4.5 17L4.2 15.8C4.15 15.55 3.95 15.35 3.7 15.3L2.5 15L3.7 14.7C3.95 14.65 4.15 14.45 4.2 14.2L4.5 13Z"
- fill="currentColor" stroke="currentColor" stroke-width="0.6" stroke-linecap="round"
- stroke-linejoin="round" />
- </svg>
- </span>
+ <t-icon name="add" size="18px" />
</template>
{{ $t('agent.createAgent') }}
</t-button>
</t-tooltip>
+ <AssistantActionButton v-if="authStore.hasRole('contributor')" icon-only
+ :label="$t('assistant.create.agentTitle')" :query="$t('assistant.prompts.startAgentCreation')" />
</div>
</div>
<p class="header-subtitle" style="--wails-draggable: drag">{{ $t('agent.subtitle') }}</p>
@@ -742,6 +728,7 @@ import { useSettingsStore } from '@/stores/settings'
import { useMenuStore } from '@/stores/menu'
import type { SharedAgentInfo, OrganizationSharedAgentItem } from '@/api/organization'
import AgentEditorModal from './AgentEditorModal.vue'
+import AssistantActionButton from '@/components/assistant/AssistantActionButton.vue'
import { useAssistantPageContext } from '@/composables/useAssistantPageContext'
import ContextualGuide from '@/components/ContextualGuide.vue'
import TenantModelsGuide from '@/components/TenantModelsGuide.vue'
diff --git a/frontend/src/views/automation/AutomationDetail.vue b/frontend/src/views/automation/AutomationDetail.vue
index ddb6ee61e..5648093f6 100644
--- a/frontend/src/views/automation/AutomationDetail.vue
+++ b/frontend/src/views/automation/AutomationDetail.vue
@@ -1,7 +1,7 @@
<template>
<SettingDrawer :visible="visible" :title="automation?.name || ''" icon="time" width="720px" :min-width="480"
:max-width="960" storage-key="setting-drawer:width:automation-detail" class="automation-detail-drawer" hide-footer
- @update:visible="(v: boolean) => !v && close()">
+ :z-index="2300" @update:visible="(v: boolean) => !v && close()">
<template #headerIcon><t-icon name="time" class="automation-detail__header-icon" /></template>
<template v-if="automation" #subtitle>
<span class="automation-detail__subtitle">
@@ -160,6 +160,9 @@
<span v-else class="automation-detail__muted">{{ t(`automation.status.${run.status}`) }}</span>
<t-icon v-if="run.session_id" name="arrow-right-up" size="16px" class="automation-run__chevron" />
</component>
+ <AssistantActionsButton v-if="run.status === 'succeeded' && run.answer" :label="t('assistant.actions.analyzeRun')"
+ :actions="runAssistantActions(run)"
+ :selection="{ field: t('automation.detail.runs'), text: run.answer.slice(0, 3000) }" />
</div>
</li>
</ul>
@@ -201,6 +204,7 @@ import { useAssistantDataChange } from '@/utils/assistantDataChange'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
import AutomationStatusTag from './AutomationStatusTag.vue'
import ChatActionIcon from '@/components/ChatActionIcon.vue'
+import AssistantActionsButton from '@/components/assistant/AssistantActionsButton.vue'
const props = defineProps<{
visible: boolean
@@ -214,6 +218,21 @@ const emit = defineEmits<{
}>()
const { t, locale } = useI18n()
+function runAssistantActions(run: AutomationRun) {
+ const previous = runs.value.filter(item => item.id !== run.id && item.status === 'succeeded'
+ && item.scheduled_at <= run.scheduled_at).slice(0, 2)
+ const source = JSON.stringify({
+ automation_id: props.automation?.id,
+ run_id: run.id,
+ session_id: run.session_id,
+ message_id: run.assistant_message_id,
+ })
+ return [
+ { key: 'summary', label: t('assistant.actions.summarizeRun'), query: t('assistant.prompts.summarizeRun', { source }) },
+ { key: 'compare', label: t('assistant.actions.compareRuns'), disabled: previous.length === 0,
+ query: t('assistant.prompts.compareRuns', { source, ids: JSON.stringify(previous.map(item => item.id)) }) },
+ ]
+}
const router = useRouter()
const PAGE = 20
diff --git a/frontend/src/views/automation/AutomationList.vue b/frontend/src/views/automation/AutomationList.vue
index de9f0edcb..268a3dc6d 100644
--- a/frontend/src/views/automation/AutomationList.vue
+++ b/frontend/src/views/automation/AutomationList.vue
@@ -11,7 +11,7 @@
:placeholder="t('menu.search')" :aria-label="t('menu.search')" clearable>
<template #prefix-icon><t-icon name="search" size="16px" /></template>
</t-input>
- <t-button variant="text" theme="default" size="small" class="automation-page__add" @click="openEditor(null)">
+ <t-button variant="text" theme="default" size="small" class="automation-page__add" @click="startCreate">
<template #icon><t-icon name="add" size="16px" /></template>
{{ t('automation.add') }}
</t-button>
@@ -83,7 +83,7 @@
</button>
</div>
</article>
- <button type="button" class="automation-card automation-card--add" @click="openEditor(null)">
+ <button type="button" class="automation-card automation-card--add" @click="startCreate">
<span class="automation-card--add__icon" aria-hidden="true"><t-icon name="add" /></span>
<span class="automation-card--add__label">{{ t('automation.add') }}</span>
<span class="automation-card--add__hint">{{ t('automation.addHint') }}</span>
@@ -91,6 +91,7 @@
</div>
</section>
+ <AssistantCreateDialog v-model:visible="assistantCreateVisible" kind="automation" @manual="openEditor(null)" />
<AutomationEditor v-model:visible="editorVisible" :automation="editing" @saved="onSaved" />
<AutomationDetail v-model:visible="detailVisible" :automation="detail"
:focus-run-id="focusRunId" @changed="onSaved" @edit="openEditor" />
@@ -118,6 +119,7 @@ import AutomationDetail from './AutomationDetail.vue'
import AutomationStatusTag from './AutomationStatusTag.vue'
import ChatActionIcon from '@/components/ChatActionIcon.vue'
import ResourceIcon from '@/components/icons/ResourceIcon.vue'
+import AssistantCreateDialog from '@/components/assistant/AssistantCreateDialog.vue'
const { t, locale } = useI18n()
const route = useRoute()
@@ -128,6 +130,10 @@ const loading = ref(true)
const query = ref('')
const busy = ref(new Set<string>())
const editorVisible = ref(false)
+const assistantCreateVisible = ref(false)
+function startCreate() {
+ assistantCreateVisible.value = true
+}
const editing = ref<Automation | null>(null)
const detailVisible = ref(false)
const detail = ref<Automation | null>(null)
diff --git a/frontend/src/views/automation/automationInteractions.test.ts b/frontend/src/views/automation/automationInteractions.test.ts
index 90b852944..f39130e59 100644
--- a/frontend/src/views/automation/automationInteractions.test.ts
+++ b/frontend/src/views/automation/automationInteractions.test.ts
@@ -19,11 +19,11 @@ const automation = {
carry_last_result: false, misfire_policy: 'skip', overlap_policy: 'skip', notify_on_success: false,
}
-function setup(t: TestContext, file: string, api: Record<string, unknown>, props: Record<string, unknown>) {
+function setup(t: TestContext, file: string, api: Record<string, unknown>, props: Record<string, unknown>, translate = (key: string, _params?: unknown) => key) {
const f = fixture(t)
const url = new URL(file, import.meta.url)
const page = f.component(url, {
- 'vue-i18n': { useI18n: () => ({ t: (key: string) => key, locale: vue.ref('en-US') }) },
+ 'vue-i18n': { useI18n: () => ({ t: translate, locale: vue.ref('en-US') }) },
'vue-router': { useRoute: () => ({ params: {}, query: {} }), useRouter: () => ({ replace() {}, push() {} }) },
'tdesign-vue-next': { MessagePlugin: { success() {}, error() {}, warning() {} } },
'@/api/automation': api,
@@ -55,6 +55,25 @@ function nodes(node: any): any[] {
? Object.values(children).flatMap(slot => typeof slot === 'function' ? nodes(slot()) : []) : [])]
}
+test('run analysis targets the chosen run and compares only earlier successful runs', async t => {
+ const { vm } = setup(t, './AutomationDetail.vue', {}, { visible: false, automation },
+ (key, params) => JSON.stringify({ key, params }))
+ const run = { id: 'chosen', status: 'succeeded', scheduled_at: '2026-10-26T12:00:00Z', session_id: 'session', assistant_message_id: 'answer' }
+ vm.runs = [
+ { ...run, id: 'newer', scheduled_at: '2026-10-27T12:00:00Z' },
+ run,
+ { ...run, id: 'failed', status: 'failed', scheduled_at: '2026-10-25T12:00:00Z' },
+ { ...run, id: 'previous', scheduled_at: '2026-10-24T12:00:00Z' },
+ ]
+ const actions = vm.runAssistantActions(run)
+ const summary = JSON.parse(actions[0].query).params
+ assert.deepEqual(JSON.parse(summary.source), { automation_id: automation.id, run_id: 'chosen', session_id: 'session', message_id: 'answer' })
+ assert.deepEqual(JSON.parse(JSON.parse(actions[1].query).params.ids), ['previous'])
+ assert.equal(actions[1].disabled, false)
+ vm.runs = [run]
+ assert.equal(vm.runAssistantActions(run)[1].disabled, true)
+})
+
test('assistant mutations refresh the automation list and open detail without replacing an editor draft', async t => {
let items = [{ ...automation }]
let calls = 0
diff --git a/frontend/src/views/chat/components/botmsg.vue b/frontend/src/views/chat/components/botmsg.vue
index 02c6044e0..e217608a6 100644
--- a/frontend/src/views/chat/components/botmsg.vue
+++ b/frontend/src/views/chat/components/botmsg.vue
@@ -80,10 +80,8 @@
</t-button>
</t-tooltip>
</t-popconfirm>
- <t-button v-if="canAskAssistant" size="small" variant="outline" shape="round"
- :title="askAssistantTitle" @click.stop="emitAskAssistant">
- <ChatActionIcon name="compass" />
- </t-button>
+ <AssistantActionsButton v-if="canAskAssistant" icon-only :label="askAssistantTitle"
+ :actions="answerAssistantActions" @before-open="emitAskAssistant" />
<t-button size="small" variant="outline" shape="round" @click.stop="handleCopyAnswer"
:title="$t('agent.copy')">
<ChatActionIcon name="copy" />
@@ -155,6 +153,7 @@ import deepThink from './deepThink.vue';
import AgentStreamDisplay from './AgentStreamDisplay.vue';
import RagPipelineProgress from './RagPipelineProgress.vue';
import ChatActionIcon from '@/components/ChatActionIcon.vue';
+import AssistantActionsButton from '@/components/assistant/AssistantActionsButton.vue';
import ChatRequestInfoButton from '@/components/ChatRequestInfoButton.vue';
import ChatCitationFloat from '@/components/ChatCitationFloat.vue';
import picturePreview from '@/components/picture-preview.vue';
@@ -288,6 +287,14 @@ const emitAskAssistant = () => {
const messageId = persistedAssistantId(props.session) || props.session?.id
if (messageId) emit('ask-assistant', messageId)
}
+const answerAssistantActions = computed(() => {
+ const source = JSON.stringify({ session_id: props.sessionId, message_id: persistedAssistantId(props.session) || props.session?.id })
+ return [
+ { key: 'document', label: t('assistant.actions.answerToDocument'), query: t('assistant.prompts.answerToDocument', { source }) },
+ { key: 'faq', label: t('assistant.actions.answerToFaq'), query: t('assistant.prompts.answerToFaq', { source }) },
+ { key: 'automation', label: t('assistant.actions.answerToAutomation'), query: t('assistant.prompts.answerToAutomation', { source }) },
+ ]
+})
const showRequestInfo = computed(() => !!(props.session?.request_id || props.session?.id));
diff --git a/frontend/src/views/knowledge/KnowledgeBase.test.ts b/frontend/src/views/knowledge/KnowledgeBase.test.ts
index 3c1a1afe5..d914781d6 100644
--- a/frontend/src/views/knowledge/KnowledgeBase.test.ts
+++ b/frontend/src/views/knowledge/KnowledgeBase.test.ts
@@ -4,7 +4,7 @@ import * as vue from 'vue'
import * as stall from '../../utils/knowledgeProcessingStall.ts'
import { change, fixture, flush } from '../../test-utils/vueFixture.ts'
-async function setup(t: TestContext) {
+async function setup(t: TestContext, translate = (key: string, _params?: unknown) => key) {
const f = fixture(t)
const route = vue.reactive({ params: { kbId: 'kb' }, query: {} })
const hook = {
@@ -24,7 +24,7 @@ async function setup(t: TestContext) {
}))
const page = f.component(new URL('./KnowledgeBase.vue', import.meta.url), {
'vue-router': { useRoute: () => route, useRouter: () => ({ replace() {} }) },
- 'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
+ 'vue-i18n': { useI18n: () => ({ t: translate }) },
'tdesign-vue-next': { MessagePlugin: { success() {}, error() {}, info() {}, warning() {} } },
'@/hooks/useKnowledgeBase': () => hook,
'@/stores/ui': { useUIStore: () => ({ clearSelectedTagIds() {} }) },
@@ -38,7 +38,8 @@ async function setup(t: TestContext) {
'@/stores/uploadTasks': { useUploadTasksStore: () => ({}) },
'@/hooks/useMarqueeSelect': { useMarqueeSelect: () => ({}) },
'@/composables/useAssistantPageContext': { useAssistantPageContext() {} },
- '@/utils/kbPermission': {}, '@/utils/knowledgeDeletion': { waitForKnowledgeDeletion }, '@/utils/knowledgeTrace': {},
+ '@/utils/kbPermission': { permissionCanEditKB: () => true, permissionCanManageKB: () => true },
+ '@/utils/knowledgeDeletion': { waitForKnowledgeDeletion }, '@/utils/knowledgeTrace': {},
'@/utils/knowledgeProcessingStall': stall, '@/api/wiki': {}, '@/api/knowledge-base': {},
'@/api/knowledge-base/index': {
listKnowledgeFolders, listKnowledgeTags: async () => ({ data: { data: [], total: 0 } }),
@@ -57,6 +58,23 @@ async function setup(t: TestContext) {
}
}
+test('batch assistant actions include only explicitly selected IDs and disable single-document comparison', async t => {
+ const f = await setup(t, (key, params) => JSON.stringify({ key, params }))
+ f.hook.cardList.value = ['selected-a', 'selected-b', 'unselected'].map(id => ({ id, parse_status: 'completed' }))
+ await flush()
+ f.vm.selectedIds = new Set(['selected-a', 'selected-b'])
+ const actions = f.vm.selectedDocumentAssistantActions
+ for (const action of actions) {
+ const params = JSON.parse(action.query).params
+ assert.equal(params.kb, 'kb')
+ assert.deepEqual(JSON.parse(params.ids), ['selected-a', 'selected-b'])
+ }
+ assert.equal(actions.find((action: any) => action.key === 'compare').disabled, false)
+ f.vm.selectedIds = new Set(['selected-a'])
+ assert.equal(f.vm.selectedDocumentAssistantActions.find((action: any) => action.key === 'compare').disabled, true)
+ assert.deepEqual(JSON.parse(JSON.parse(actions[0].query).params.ids), ['selected-a', 'selected-b'])
+})
+
test('refreshes files and folders for the open KB and ignores unrelated areas and KBs', async t => {
const f = await setup(t)
f.emit(change('knowledge.create_manual', { knowledge_base_id: ['other'] }))
diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vue
index 15bcc01e5..bbbaae00c 100644
--- a/frontend/src/views/knowledge/KnowledgeBase.vue
+++ b/frontend/src/views/knowledge/KnowledgeBase.vue
@@ -48,6 +48,7 @@ import FAQEntryManager from './components/FAQEntryManager.vue';
import DocumentListView from './components/DocumentListView.vue';
import DocumentCardView from './components/DocumentCardView.vue';
import DocumentBatchBar from './components/DocumentBatchBar.vue';
+import AssistantActionsButton from '@/components/assistant/AssistantActionsButton.vue';
import KbUploadSourceDropdown from './components/KbUploadSourceDropdown.vue';
import KbFolderTree from './components/KbFolderTree.vue';
import BatchTagDialog from './components/BatchTagDialog.vue';
@@ -484,6 +485,17 @@ watch(viewMode, (v) => {
// Multi-select state — shared between grid and list views.
// Vue 3.5 tracks Set#add/delete natively, so direct mutation is reactive.
const selectedIds = ref<Set<string>>(new Set());
+const selectedDocumentAssistantActions = computed(() => {
+ const scope = { kb: kbId.value, ids: JSON.stringify([...selectedIds.value]) };
+ return [
+ { key: 'summarize', label: t('assistant.actions.summarizeSelected'), query: t('assistant.prompts.summarizeDocuments', scope) },
+ { key: 'compare', label: t('assistant.actions.compareDocuments'), query: t('assistant.prompts.compareDocuments', scope), disabled: selectedIds.value.size < 2 },
+ ...(canMutateKnowledge.value ? [
+ { key: 'tags', label: t('assistant.actions.suggestTags'), query: t('assistant.prompts.tagDocuments', scope) },
+ { key: 'folders', label: t('assistant.actions.organizeDocuments'), query: t('assistant.prompts.organizeDocuments', scope) },
+ ] : []),
+ ];
+});
let lastSelectedIndex = -1;
const batchDeleting = ref(false);
const batchReparsing = ref(false);
@@ -2737,7 +2749,13 @@ const handleKBEditorSuccess = (kbIdValue: string) => {
:show-move-to-folder="canEdit" :folder-options="folderOptions"
@cancel="handleBatchCancel" @delete="confirmBatchDelete" @reparse="confirmBatchReparse"
@batch-tag="handleBatchTag" @download="handleBatchDownload" @select-loaded="toggleSelectAll(true)"
- @move-to-folder="(path: string) => moveKnowledgeIntoFolder(Array.from(selectedIds), path)" />
+ @move-to-folder="(path: string) => moveKnowledgeIntoFolder(Array.from(selectedIds), path)">
+ <template #assistant>
+ <AssistantActionsButton v-if="selectedIds.size" :label="$t('assistant.actions.processSelected')"
+ :actions="selectedDocumentAssistantActions"
+ :disabled="batchDeleting || batchReparsing || batchTagging || batchDownloading" />
+ </template>
+ </DocumentBatchBar>
</div>
</div>
</div>
diff --git a/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue b/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue
index 24301e19b..6b8859be7 100644
--- a/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue
+++ b/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue
@@ -106,23 +106,37 @@
<div v-if="!isFAQ && formData.indexingStrategy.wikiEnabled" class="form-item">
<label class="form-label">{{ $t('knowledgeEditor.wiki.contentInstructionsLabel') }}</label>
<p class="form-tip">{{ $t('knowledgeEditor.wiki.contentInstructionsTip') }}</p>
- <t-textarea
- v-model="formData.wikiConfig.contentInstructions"
- :placeholder="$t('knowledgeEditor.wiki.contentInstructionsPlaceholder')"
- :maxlength="4000"
- :autosize="{ minRows: 3, maxRows: 8 }"
- />
+ <div class="wiki-instructions-input">
+ <t-textarea
+ v-model="formData.wikiConfig.contentInstructions"
+ :placeholder="$t('knowledgeEditor.wiki.contentInstructionsPlaceholder')"
+ :maxlength="4000"
+ :autosize="{ minRows: 3, maxRows: 8 }"
+ />
+ <AssistantActionButton class="wiki-instructions-action"
+ :label="$t(formData.wikiConfig.contentInstructions.trim() ? 'assistant.actions.refineRules' : 'assistant.actions.writePrompt')"
+ :query="$t(formData.wikiConfig.contentInstructions.trim() ? 'assistant.prompts.refineWikiRules' : 'assistant.prompts.writeWikiRules', { field: $t('knowledgeEditor.wiki.contentInstructionsLabel') })"
+ :selection="{ field: $t('knowledgeEditor.wiki.contentInstructionsLabel'), text: formData.wikiConfig.contentInstructions }"
+ :disabled="saving || loading" />
+ </div>
</div>
<div v-if="!isFAQ && formData.indexingStrategy.wikiEnabled" class="form-item">
<label class="form-label">{{ $t('knowledgeEditor.wiki.extractionInstructionsLabel') }}</label>
<p class="form-tip">{{ $t('knowledgeEditor.wiki.extractionInstructionsTip') }}</p>
- <t-textarea
- v-model="formData.wikiConfig.extractionInstructions"
- :placeholder="$t('knowledgeEditor.wiki.extractionInstructionsPlaceholder')"
- :maxlength="4000"
- :autosize="{ minRows: 3, maxRows: 8 }"
- />
+ <div class="wiki-instructions-input">
+ <t-textarea
+ v-model="formData.wikiConfig.extractionInstructions"
+ :placeholder="$t('knowledgeEditor.wiki.extractionInstructionsPlaceholder')"
+ :maxlength="4000"
+ :autosize="{ minRows: 3, maxRows: 8 }"
+ />
+ <AssistantActionButton class="wiki-instructions-action"
+ :label="$t(formData.wikiConfig.extractionInstructions.trim() ? 'assistant.actions.refineRules' : 'assistant.actions.writePrompt')"
+ :query="$t(formData.wikiConfig.extractionInstructions.trim() ? 'assistant.prompts.refineWikiRules' : 'assistant.prompts.writeWikiRules', { field: $t('knowledgeEditor.wiki.extractionInstructionsLabel') })"
+ :selection="{ field: $t('knowledgeEditor.wiki.extractionInstructionsLabel'), text: formData.wikiConfig.extractionInstructions }"
+ :disabled="saving || loading" />
+ </div>
</div>
<div class="form-item" data-guide="kb-create-name">
@@ -651,6 +665,7 @@ import DataSourceSettings from './settings/DataSourceSettings.vue'
import KnowledgeBaseActivitySettings from './settings/KnowledgeBaseActivitySettings.vue'
import ImagePipelineSettings from './ImagePipelineSettings.vue'
import { useI18n } from 'vue-i18n'
+import AssistantActionButton from '@/components/assistant/AssistantActionButton.vue'
const uiStore = useUIStore()
const authStore = useAuthStore()
@@ -1972,6 +1987,20 @@ watch(() => chatResources.allModels, (list) => {
</script>
<style scoped lang="less">
+.wiki-instructions-input {
+ position: relative;
+
+ .wiki-instructions-action {
+ position: absolute;
+ left: 8px;
+ bottom: 8px;
+ }
+
+ :deep(.t-textarea__inner) {
+ padding-bottom: 44px;
+ }
+}
+
// 图片属性面板(可观察属性 / OCR 触发条件 / 观察失败兜底)
// 文案全部来自后端属性注册表(人话名 + 每个取值的含义),前端只做翻译覆盖,
// 因此新增属性无需改这里。铺在所在设置区里、不套独立底色块(与整体风格一致)。
diff --git a/frontend/src/views/knowledge/components/DocumentBatchBar.vue b/frontend/src/views/knowledge/components/DocumentBatchBar.vue
index 86cd9803d..3f41e78a6 100644
--- a/frontend/src/views/knowledge/components/DocumentBatchBar.vue
+++ b/frontend/src/views/knowledge/components/DocumentBatchBar.vue
@@ -51,6 +51,7 @@ const folderPickerVisible = ref(false);
</t-button>
</div>
<div class="batch-bar-actions">
+ <slot name="assistant" />
<t-tooltip v-if="canDownload" :content="t('knowledgeBase.batchDownloadHint')">
<span class="batch-download-trigger">
<t-button theme="primary" size="small" :loading="downloadLoading"
diff --git a/frontend/src/views/knowledge/components/FAQEntryManager.vue b/frontend/src/views/knowledge/components/FAQEntryManager.vue
index 2aabc1534..0c46d3bed 100644
--- a/frontend/src/views/knowledge/components/FAQEntryManager.vue
+++ b/frontend/src/views/knowledge/components/FAQEntryManager.vue
@@ -454,7 +454,14 @@
<!-- 相似问 -->
<div class="setting-row vertical setting-row-optional setting-row-similar">
<div class="setting-info">
- <label class="optional-label">{{ $t('knowledgeEditor.faq.similarQuestions') }}</label>
+ <div class="setting-label-row">
+ <label class="optional-label">{{ $t('knowledgeEditor.faq.similarQuestions') }}</label>
+ <AssistantActionButton v-if="editorForm.standard_question.trim()"
+ :label="$t('assistant.actions.suggestFaqQuestions')"
+ :query="$t('assistant.prompts.suggestFaqQuestions', { count: Math.max(0, 10 - editorForm.similar_questions.length) })"
+ :selection="faqAssistantSelection"
+ :disabled="savingEntry || editorForm.similar_questions.length >= 10" />
+ </div>
<p class="desc optional-desc">{{ $t('knowledgeEditor.faq.similarQuestionsDesc') }}</p>
</div>
<div class="setting-control">
@@ -520,9 +527,15 @@
<div class="setting-control">
<div class="textarea-container">
<div class="full-width-input-wrapper textarea-wrapper">
- <t-textarea v-model="answerInput" :placeholder="$t('knowledgeEditor.faq.answerPlaceholder')"
- :autosize="{ minRows: 3, maxRows: 6 }" class="full-width-textarea" @keydown.ctrl.enter="addAnswer"
- @keydown.meta.enter="addAnswer" />
+ <div class="faq-answer-draft">
+ <t-textarea v-model="answerInput" :placeholder="$t('knowledgeEditor.faq.answerPlaceholder')"
+ :autosize="{ minRows: 3, maxRows: 6 }" class="full-width-textarea" @keydown.ctrl.enter="addAnswer"
+ @keydown.meta.enter="addAnswer" />
+ <AssistantActionButton v-if="editorForm.standard_question.trim()" class="faq-answer-action"
+ :label="$t(answerInput.trim() ? 'assistant.actions.refineAnswer' : 'assistant.actions.writeAnswer')"
+ :query="$t(answerInput.trim() ? 'assistant.prompts.refineFaqAnswer' : 'assistant.prompts.writeFaqAnswer')"
+ :selection="faqAnswerSelection" :disabled="savingEntry || editorForm.answers.length >= 5" />
+ </div>
<t-button theme="primary" variant="outline"
:disabled="!answerInput.trim() || editorForm.answers.length >= 5" @click="addAnswer"
class="add-item-btn" size="small">
@@ -856,6 +869,7 @@
<script setup lang="ts">
import { useAssistantDataChange } from '@/utils/assistantDataChange'
+import AssistantActionButton from '@/components/assistant/AssistantActionButton.vue'
import { ref, reactive, watch, onMounted, computed, nextTick, onUnmounted, h } from 'vue'
import KnowledgeTagFilter from './KnowledgeTagFilter.vue'
import { MessagePlugin, Icon as TIcon } from 'tdesign-vue-next'
@@ -1173,6 +1187,25 @@ const answerInput = ref('')
const similarInput = ref('')
const negativeInput = ref('')
+const faqAnswerSelection = computed(() => ({
+ field: t('knowledgeEditor.faq.answers'),
+ text: JSON.stringify({
+ standard_question: editorForm.standard_question,
+ draft_answer: answerInput.value,
+ existing_answers: editorForm.answers,
+ }, null, 2),
+}))
+
+const faqAssistantSelection = computed(() => ({
+ field: t('knowledgeEditor.faq.similarQuestions'),
+ text: JSON.stringify({
+ standard_question: editorForm.standard_question,
+ existing_similar_questions: [...editorForm.similar_questions, similarInput.value].filter(Boolean),
+ negative_questions: [...editorForm.negative_questions, negativeInput.value].filter(Boolean),
+ answers: [...editorForm.answers, answerInput.value].filter(Boolean),
+ }, null, 2),
+}))
+
const importVisible = ref(false)
const fileInputRef = ref<HTMLInputElement | null>(null)
const importState = reactive({
@@ -2781,6 +2814,15 @@ watch(() => entries.value.map(e => ({
</script>
<style scoped lang="less">
+.faq-answer-draft {
+ position: relative;
+ flex: 1;
+ min-width: 0;
+
+ .faq-answer-action { position: absolute; left: 8px; bottom: 8px; }
+ :deep(.t-textarea__inner) { padding-bottom: 44px; }
+}
+
.faq-manager {
display: flex;
flex-direction: column;
@@ -4848,6 +4890,18 @@ watch(() => entries.value.map(e => ({
max-width: 65%;
padding-right: 24px;
+ .setting-label-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ margin-bottom: 4px;
+
+ label {
+ margin-bottom: 0;
+ }
+ }
+
label {
font-size: var(--app-text-lg);
font-weight: 500;
diff --git a/frontend/src/views/knowledge/settings/DataSourceSyncLogs.vue b/frontend/src/views/knowledge/settings/DataSourceSyncLogs.vue
index 76dc7b221..e53ac23f6 100644
--- a/frontend/src/views/knowledge/settings/DataSourceSyncLogs.vue
+++ b/frontend/src/views/knowledge/settings/DataSourceSyncLogs.vue
@@ -2,6 +2,7 @@
import { ref, watch, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { getSyncLogs, type SyncLog, type SyncItemError } from '@/api/datasource'
+import AssistantActionButton from '@/components/assistant/AssistantActionButton.vue'
const props = defineProps<{
dataSourceId: string
@@ -285,6 +286,23 @@ const groupedLogs = computed(() => {
<div v-else-if="log.error_message" class="tl-error">
{{ log.error_message }}
</div>
+ <AssistantActionButton
+ v-if="log.status === 'failed' || log.status === 'partial' || log.items_failed > 0"
+ :label="t('assistant.actions.diagnose')"
+ :query="t('assistant.prompts.syncFailure', { source: props.dataSourceName || props.dataSourceId, id: props.dataSourceId, log: log.id })"
+ :selection="{
+ field: t('datasource.syncHistory'),
+ text: JSON.stringify({
+ data_source_id: props.dataSourceId,
+ sync_log_id: log.id,
+ status: log.status,
+ started_at: log.started_at,
+ items_total: log.items_total,
+ items_failed: log.items_failed,
+ error_message: log.error_message.slice(0, 1000),
+ error_samples: failedItems(log).slice(0, 5).map(e => formatSyncError(e).slice(0, 300)),
+ }, null, 2),
+ }" />
<!-- Per-item failures: which documents failed and why.
The true count is items_failed (a bounded int); result.errors
diff --git a/frontend/src/views/knowledge/settings/KBChunkingDebug.test.ts b/frontend/src/views/knowledge/settings/KBChunkingDebug.test.ts
new file mode 100644
index 000000000..232f412d8
--- /dev/null
+++ b/frontend/src/views/knowledge/settings/KBChunkingDebug.test.ts
@@ -0,0 +1,112 @@
+import assert from 'node:assert/strict'
+import test, { type TestContext } from 'node:test'
+import { reactive } from 'vue'
+import { fixture } from '../../../test-utils/vueFixture.ts'
+import type { PreviewChunkingRequest, PreviewChunkingResponse } from '../../../types/chunker.ts'
+
+const output: PreviewChunkingResponse = {
+ selected_tier: 'heading', tier_chain: ['heading'], rejected: [],
+ profile: {
+ total_chars: 12, total_lines: 2, avg_line_len: 6, std_line_len: 0,
+ md_heading_counts: { '1': 1 }, md_heading_total: 1, numbered_section_count: 0,
+ all_caps_short_line_count: 0, blank_paragraph_breaks: 0, form_feed_count: 0,
+ visual_sep_count: 0, german_chapter_count: 0, english_chapter_count: 0,
+ chinese_chapter_count: 0, repeated_footer_count: 0, has_tables: false,
+ has_code: false, code_ratio: 0, detected_langs: ['en'],
+ },
+ chunks: [{ seq: 0, start: 0, end: 12, size_chars: 12, size_tokens_approx: 3, content: '# Title\nText' }],
+ stats: { count: 1, avg_chars: 12, min_chars: 12, max_chars: 12, stddev_chars: 0 },
+}
+
+function mount(t: TestContext, previewChunking: (input: PreviewChunkingRequest) => Promise<unknown>) {
+ const config = reactive({
+ chunkSize: 512, chunkOverlap: 50, separators: ['\n\n'], enableParentChild: false,
+ parentChunkSize: 1024, childChunkSize: 256, strategy: 'auto', tokenLimit: 256,
+ languages: ['en'],
+ })
+ const errors = t.mock.fn()
+ const { vm } = fixture(t).component(new URL('./KBChunkingDebug.vue', import.meta.url), {
+ 'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
+ 'tdesign-vue-next': { MessagePlugin: { error: errors } },
+ 'tdesign-icons-vue-next': {},
+ '@/api/chunker': { previewChunking },
+ './chunkingSamples': { CHUNKING_SAMPLES: [{ id: 'preset', text: 'Preset text' }], DEFAULT_SAMPLE_ID: 'preset' },
+ }, { config })
+ return { vm, config, errors }
+}
+
+test('assistant analysis keeps the input and parameters that produced the visible preview', async t => {
+ let complete!: (value: unknown) => void
+ const previewChunking = t.mock.fn((_input: PreviewChunkingRequest) => new Promise(resolve => { complete = resolve }))
+ const { vm, config } = mount(t, previewChunking)
+ vm.sample = '# Title\nText'
+ const pending = vm.runPreview()
+ assert.equal(vm.assistantPreviewSelection, undefined)
+
+ // The form remains editable while the request is pending and after it finishes.
+ vm.sample = 'Unpreviewed draft'
+ config.chunkSize = 2048
+ config.separators.push('.')
+ config.languages.push('zh')
+ const submitted = previewChunking.mock.calls[0].arguments[0]
+ assert.equal(submitted.text, '# Title\nText')
+ assert.equal(submitted.chunking_config.chunk_size, 512)
+ assert.deepEqual(Array.from(submitted.chunking_config.separators), ['\n\n'])
+ assert.deepEqual(Array.from(submitted.chunking_config.languages!), ['en'])
+
+ complete({ success: true, data: output })
+ await pending
+ const selection = vm.assistantPreviewSelection
+ assert.match(selection.text, /Original text excerpt:\n# Title\nText/)
+ assert.match(selection.text, /"chunk_size":512/)
+ assert.match(selection.text, /Chunk #0 \[0–12\]/)
+ assert.doesNotMatch(selection.text, /Unpreviewed draft|2048/)
+ vm.sample = 'Another draft'
+ config.chunkOverlap = 100
+ assert.equal(vm.assistantPreviewSelection.text, selection.text)
+})
+
+test('assistant context is cleared for a new or failed preview and when loading a preset', async t => {
+ let complete!: (value: unknown) => void
+ let fail!: (reason: Error) => void
+ const { vm, errors } = mount(t, () => new Promise((resolve, reject) => { complete = resolve; fail = reject }))
+ t.mock.method(console, 'error', () => {})
+ vm.sample = 'First document'
+ let pending = vm.runPreview()
+ complete({ success: true, data: output })
+ await pending
+ assert.ok(vm.assistantPreviewSelection)
+
+ pending = vm.runPreview()
+ assert.equal(vm.assistantPreviewSelection, undefined)
+ fail(new Error('Preview unavailable'))
+ await pending
+ assert.equal(vm.assistantPreviewSelection, undefined)
+ assert.equal(vm.error, 'Preview unavailable')
+ assert.equal(errors.mock.callCount(), 1)
+
+ pending = vm.runPreview()
+ complete({ success: true, data: output })
+ await pending
+ vm.loadSample('preset')
+ assert.equal(vm.sample, 'Preset text')
+ assert.equal(vm.assistantPreviewSelection, undefined)
+})
+
+test('large previews retain both original and chunk excerpts within the page-selection budget', async t => {
+ const chunks = Array.from({ length: 10 }, (_, seq) => ({
+ seq, start: seq * 2000, end: (seq + 1) * 2000, size_chars: 2000, size_tokens_approx: 500,
+ content: `Chunk ${seq} content ` + '文'.repeat(2000),
+ }))
+ const { vm } = mount(t, async () => ({ success: true, data: { ...output, chunks } }))
+ vm.sample = 'Original text ' + '原'.repeat(10000)
+ await vm.runPreview()
+ const text = vm.assistantPreviewSelection.text
+ assert.ok(text.length <= 4000)
+ assert.match(text, /not the full document/)
+ assert.match(text, /Original text excerpt:\nOriginal text/)
+ assert.match(text, /"chunk_size":512/)
+ assert.match(text, /Statistics:/)
+ for (let seq = 0; seq < 3; seq++) assert.ok(text.includes(`Chunk ${seq} content`))
+ assert.doesNotMatch(text, /Chunk 3 content/)
+})
diff --git a/frontend/src/views/knowledge/settings/KBChunkingDebug.vue b/frontend/src/views/knowledge/settings/KBChunkingDebug.vue
index fcf539920..1d0b0c9d4 100644
--- a/frontend/src/views/knowledge/settings/KBChunkingDebug.vue
+++ b/frontend/src/views/knowledge/settings/KBChunkingDebug.vue
@@ -25,7 +25,7 @@
:close-on-overlay-click="true"
:destroy-on-close="false"
attach="body"
- :z-index="3000"
+ :z-index="2300"
>
<div class="drawer-body">
<!-- Input section -->
@@ -99,6 +99,9 @@
<span v-if="fallbackWarning" class="fallback-warning">
{{ $t('knowledgeEditor.chunking.debug.fallbackWarning') }}
</span>
+ <AssistantActionButton class="chunk-analysis-action"
+ :label="$t('assistant.actions.analyzeChunks')" :query="$t('assistant.prompts.analyzeChunks')"
+ :selection="assistantPreviewSelection" />
</div>
<div v-if="(result.rejected || []).length > 0" class="tier-row">
<span class="result-label">{{ $t('knowledgeEditor.chunking.debug.rejected') }}:</span>
@@ -216,7 +219,8 @@ import {
ErrorCircleIcon,
} from 'tdesign-icons-vue-next'
import { previewChunking } from '@/api/chunker'
-import type { PreviewChunkingResponse, StrategyTier } from '@/types/chunker'
+import type { PreviewChunkingRequest, PreviewChunkingResponse, StrategyTier } from '@/types/chunker'
+import AssistantActionButton from '@/components/assistant/AssistantActionButton.vue'
import { CHUNKING_SAMPLES, DEFAULT_SAMPLE_ID } from './chunkingSamples'
interface Props {
@@ -244,8 +248,29 @@ const sample = ref('')
const loading = ref(false)
const error = ref('')
const result = ref<PreviewChunkingResponse | null>(null)
+const previewInput = ref<PreviewChunkingRequest | null>(null)
const expandedChunks = ref(new Set<number>())
+const assistantPreviewSelection = computed(() => {
+ const input = previewInput.value
+ const output = result.value
+ if (!input || !output) return undefined
+ return {
+ field: t('knowledgeEditor.chunking.debug.toggle'),
+ // The backend accepts at most 4000 selection characters. Keep parameters,
+ // statistics and both kinds of excerpt within that budget.
+ text: [
+ 'Preview excerpts (not the full document):',
+ `Parameters: ${JSON.stringify(input.chunking_config)}`,
+ `Selected strategy: ${output.selected_tier}`,
+ `Statistics: ${JSON.stringify(output.stats)}`,
+ `Original text excerpt:\n${input.text.slice(0, 900)}`,
+ ...output.chunks.slice(0, 3).map(chunk =>
+ `Chunk #${chunk.seq} [${chunk.start}–${chunk.end}], ${chunk.size_chars} characters:\n${chunk.content.slice(0, 600)}`),
+ ].join('\n\n').slice(0, 4000),
+ }
+})
+
const samples = CHUNKING_SAMPLES
// Auto-load the default preset the first time the user opens the drawer with
@@ -264,6 +289,7 @@ const loadSample = (id: string) => {
// Clear any previous run so the user isn't looking at stale results
// attributed to the old text.
result.value = null
+ previewInput.value = null
error.value = ''
expandedChunks.value = new Set()
}
@@ -277,25 +303,27 @@ const runPreview = async () => {
loading.value = true
error.value = ''
result.value = null
+ previewInput.value = null
expandedChunks.value = new Set()
try {
// Send all fields explicitly (including empty / 0 / []) so the
// preview faithfully reflects what would happen on save. Mirrors
// the buildSubmitData convention in KnowledgeBaseEditorModal.
- const resp = await previewChunking({
+ const input: PreviewChunkingRequest = {
text: sample.value,
chunking_config: {
chunk_size: props.config.chunkSize,
chunk_overlap: props.config.chunkOverlap,
- separators: props.config.separators,
+ separators: [...props.config.separators],
enable_parent_child: props.config.enableParentChild,
parent_chunk_size: props.config.parentChunkSize,
child_chunk_size: props.config.childChunkSize,
strategy: props.config.strategy ?? '',
token_limit: props.config.tokenLimit ?? 0,
- languages: props.config.languages ?? []
+ languages: [...(props.config.languages ?? [])]
}
- })
+ }
+ const resp = await previewChunking(input)
// The axios interceptor in utils/request.ts already unwraps the
// outer envelope and returns the response body. So resp here is
// { success: true, data: PreviewChunkingResponse } directly.
@@ -310,6 +338,7 @@ const runPreview = async () => {
if (!resp.data) {
throw new Error('response missing data')
}
+ previewInput.value = input
result.value = resp.data
} catch (e: any) {
// Pull a useful message out of the error shapes our request layer
@@ -361,6 +390,10 @@ const tierTheme = (tier: StrategyTier) => {
</script>
<style lang="less" scoped>
+.chunk-analysis-action {
+ margin-left: auto;
+}
+
.kb-chunking-debug {
flex-shrink: 0;
}
diff --git a/frontend/src/views/knowledge/settings/KnowledgeBaseActivityAssistant.test.ts b/frontend/src/views/knowledge/settings/KnowledgeBaseActivityAssistant.test.ts
new file mode 100644
index 000000000..da41332dc
--- /dev/null
+++ b/frontend/src/views/knowledge/settings/KnowledgeBaseActivityAssistant.test.ts
@@ -0,0 +1,31 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { fixture } from '../../../test-utils/vueFixture.ts'
+
+test('activity summaries preserve the exact loaded IDs and server-side filters', t => {
+ const { vm } = fixture(t).component(new URL('./KnowledgeBaseActivitySettings.vue', import.meta.url), {
+ 'vue-i18n': { useI18n: () => ({ t: (key: string, params: unknown) => JSON.stringify({ key, params }), te: () => false, tm: () => ({}) }) },
+ '@/stores/auth': { useAuthStore: () => ({}) },
+ '@/i18n/auditActionRegistry': { AUDIT_ACTION_I18N_ROOTS: { kbActivity: 'activity' } },
+ '@/i18n/auditActionLabel': { auditActionLabel: () => '' },
+ '@/api/knowledge-base': {},
+ }, { kbId: 'kb-1', active: false })
+ vm.action = 'knowledge.update'
+ vm.outcome = 'success'
+ vm.entries = [{ id: 20, created_at: '2026-10-26T12:00:00Z' }, { id: 12, created_at: '2026-10-25T12:00:00Z' }]
+ vm.hasMore = true
+ const scope = JSON.parse(JSON.parse(vm.activityAssistantQuery).params.scope)
+ assert.deepEqual(scope.loaded_entry_ids, [20, 12])
+ assert.equal(scope.knowledge_base_id, 'kb-1')
+ assert.equal(scope.action, 'knowledge.update')
+ assert.equal(scope.outcome, 'success')
+ assert.equal(scope.has_more, true)
+ vm.entries = [{ id: 7, created_at: '2026-10-24T12:00:00Z' }]
+ vm.action = undefined
+ vm.outcome = 'failed'
+ const changed = JSON.parse(JSON.parse(vm.activityAssistantQuery).params.scope)
+ assert.deepEqual(changed.loaded_entry_ids, [7])
+ assert.equal(changed.action, undefined)
+ assert.equal(changed.outcome, 'failed')
+ assert.deepEqual(scope.loaded_entry_ids, [20, 12])
+})
diff --git a/frontend/src/views/knowledge/settings/KnowledgeBaseActivitySettings.vue b/frontend/src/views/knowledge/settings/KnowledgeBaseActivitySettings.vue
index baaf957fe..f590e6222 100644
--- a/frontend/src/views/knowledge/settings/KnowledgeBaseActivitySettings.vue
+++ b/frontend/src/views/knowledge/settings/KnowledgeBaseActivitySettings.vue
@@ -16,14 +16,17 @@
:class="{ 'sq-refresh-spin': loading }"
/>
</button>
+ <AssistantActionButton v-if="entries.length" icon-only
+ :label="t('assistant.actions.summarizeActivity', { count: entries.length })"
+ :query="activityAssistantQuery" :disabled="loading" />
</div>
<p class="section-desc">{{ t('knowledgeEditor.activity.description') }}</p>
- <p v-if="hasActiveFilters" class="kb-activity-filter-bar">
+ <div v-if="hasActiveFilters" class="kb-activity-filter-bar">
<span>{{ filterSummaryText }}</span>
<button type="button" class="kb-activity-clear-filters" @click="clearFilters">
{{ t('knowledgeEditor.activity.clearFilters') }}
</button>
- </p>
+ </div>
</div>
<div class="section-body kb-activity-body">
@@ -265,6 +268,7 @@
<script setup lang="ts">
import { computed, nextTick, onUnmounted, ref, watch } from 'vue'
+import AssistantActionButton from '@/components/assistant/AssistantActionButton.vue'
import { useI18n } from 'vue-i18n'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
import { AUDIT_ACTION_I18N_ROOTS } from '@/i18n/auditActionRegistry'
@@ -348,6 +352,17 @@ const columns = computed(() => [
])
const hasActiveFilters = computed(() => Boolean(action.value || outcome.value))
+const activityAssistantQuery = computed(() => t('assistant.prompts.summarizeActivity', {
+ scope: JSON.stringify({
+ knowledge_base_id: props.kbId,
+ action: action.value,
+ outcome: outcome.value,
+ loaded_entry_ids: entries.value.map(entry => entry.id),
+ newest_at: entries.value[0]?.created_at,
+ oldest_at: entries.value.at(-1)?.created_at,
+ has_more: hasMore.value,
+ }),
+}))
const filterSummaryText = computed(() => {
const parts: string[] = []
diff --git a/frontend/src/views/knowledge/wiki/WikiBrowser.vue b/frontend/src/views/knowledge/wiki/WikiBrowser.vue
index a57c1f5d4..12a9b5d0e 100644
--- a/frontend/src/views/knowledge/wiki/WikiBrowser.vue
+++ b/frontend/src/views/knowledge/wiki/WikiBrowser.vue
@@ -450,11 +450,8 @@
})
}}</span>
</div>
- <t-button v-if="props.canEdit" size="small" theme="primary" variant="base"
- @click="triggerAutoFix">
- <template #icon><t-icon name="tools" /></template>
- {{ $t('knowledgeEditor.wikiBrowser.issueFixBtn') }}
- </t-button>
+ <AssistantButton v-if="props.canEdit"
+ :label="$t('knowledgeEditor.wikiBrowser.issueFixBtn')" @click="triggerAutoFix" />
</div>
<div class="wiki-issue-popup-list">
<div v-for="issue in pageIssues" :key="issue.id" class="wiki-issue-popup-item">
@@ -485,11 +482,8 @@
}) }}
</span>
<div v-if="props.canEdit" class="wiki-issue-popup-actions">
- <span class="wiki-issue-popup-action" @click="triggerFixIssue(issue)"
- style="margin-right: 12px; font-weight: 500;">
- <t-icon name="tools" style="margin-right: 4px;" />{{
- $t('knowledgeEditor.wikiBrowser.issueFixSingle') }}
- </span>
+ <AssistantButton :label="$t('knowledgeEditor.wikiBrowser.issueFixSingle')"
+ @click="triggerFixIssue(issue)" />
<span class="wiki-issue-popup-action"
style="color: var(--td-text-color-placeholder);"
@click="handleIssueIgnore(issue.id)">{{
@@ -547,6 +541,8 @@
</t-button>
</template>
<template v-else>
+ <AssistantActionsButton icon-only :label="$t('assistant.actions.readContent')"
+ :actions="readingAssistantActions" />
<t-tooltip v-if="props.canEdit" :content="$t('knowledgeEditor.wikiBrowser.editBtn')"
placement="top">
<button type="button" class="wiki-action-btn"
@@ -729,7 +725,7 @@
</span>
<div class="wiki-issue-popup-actions">
<span class="wiki-issue-popup-action" @click="navigateToSlugAndFix(issue.slug)"
- style="margin-right: 12px; font-weight: 500;">
+ style="font-weight: 500;">
<t-icon name="arrow-right-circle" style="margin-right: 4px;" />{{
$t('knowledgeEditor.wikiBrowser.issueGoFix') }}
</span>
@@ -834,6 +830,8 @@ import { resolveWikiBacklinkTitle } from './wikiBacklinkTitles'
import { buildGraphLayout, graphNodeRadius, stepGraphLayout, visibleGraphLabels, graphPointBounds, initialGraphViewport, graphClusterOutline, graphLandmarkTitle, type GraphBounds, type GraphCluster } from './wikiGraphLayout'
import { getKnowledgeDetails } from '@/api/knowledge-base'
import { useAssistantStore } from '@/stores/assistant'
+import AssistantButton from '@/components/assistant/AssistantButton.vue'
+import AssistantActionsButton from '@/components/assistant/AssistantActionsButton.vue'
import { useAssistantPageContext } from '@/composables/useAssistantPageContext'
import {
listWikiPages,
@@ -1003,6 +1001,14 @@ const activeSystemView = ref<'' | 'index'>('')
// the scenes so clearing the query can snap back without re-fetching.
const searchResults = ref<WikiPage[] | null>(null)
const pageIssues = ref<WikiPageIssue[]>([])
+const readingAssistantActions = computed(() => {
+ const source = JSON.stringify({ knowledge_base_id: props.knowledgeBaseId, wiki_slug: selectedPage.value?.slug });
+ return [
+ { key: 'summary', label: t('assistant.actions.readSummary'), query: t('assistant.prompts.readSummary', { source }) },
+ { key: 'steps', label: t('assistant.actions.readSteps'), query: t('assistant.prompts.readSteps', { source }) },
+ { key: 'faq', label: t('assistant.actions.extractFaq'), query: t('assistant.prompts.extractFaq', { source }) },
+ ];
+})
const showIssuesBox = ref(false)
useAssistantPageContext(() => {
const page = selectedPage.value
@@ -7001,6 +7007,7 @@ span.graph-focus-name {
.wiki-issue-popup-actions {
display: flex;
align-items: center;
+ gap: 12px;
}
.wiki-issue-popup-action {
diff --git a/frontend/src/views/settings/Settings.vue b/frontend/src/views/settings/Settings.vue
index 0d9f2b5e0..951e049c1 100644
--- a/frontend/src/views/settings/Settings.vue
+++ b/frontend/src/views/settings/Settings.vue
@@ -38,6 +38,7 @@
<path d="M5.5 10h4M5.5 12.5h2.5" stroke="currentColor" stroke-width="1.2"
stroke-linecap="round" />
</svg>
+ <ResourceIcon v-else-if="item.key === 'assistant'" type="assistant" :size="17" class="nav-icon" />
<span v-else-if="item.emoji" class="nav-icon nav-icon-emoji">{{ item.emoji }}</span>
<t-icon v-else :name="item.icon" class="nav-icon" />
<span class="nav-label">{{ item.label }}</span>
@@ -208,6 +209,7 @@ import { useI18n } from 'vue-i18n'
import { MessagePlugin } from 'tdesign-vue-next'
import { useModalShell } from '@/composables/useModalShell'
import SettingsModalShell from '@/components/SettingsModalShell.vue'
+import ResourceIcon from '@/components/icons/ResourceIcon.vue'
import SystemInfo from './SystemInfo.vue'
import TenantInfo from './TenantInfo.vue'
import UserProfile from './UserProfile.vue'
@@ -377,7 +379,7 @@ const navItems = computed(() => {
{ key: 'system-audit-log', icon: 'history', label: t('system.globalSettings.audit.tabLabel') },
{ key: 'userprofile', icon: 'user', label: t('userProfile.title') },
{ key: 'mymemory', icon: 'bookmark', label: t('memorySettings.title') },
- { key: 'assistant', icon: 'compass', label: t('assistantSettings.title') },
+ { key: 'assistant', icon: 'assistant', label: t('assistantSettings.title') },
{ key: 'envvars', icon: 'key', label: envNavLabel() },
{ key: 'tenant', icon: 'user-circle', label: t('settings.tenantInfo') },
{ key: 'members', icon: 'usergroup', label: t('tenantMember.title') },
diff --git a/frontend/src/views/settings/components/McpMetadataPanel.vue b/frontend/src/views/settings/components/McpMetadataPanel.vue
index 00f2993c1..6df3c4be6 100644
--- a/frontend/src/views/settings/components/McpMetadataPanel.vue
+++ b/frontend/src/views/settings/components/McpMetadataPanel.vue
@@ -19,6 +19,8 @@
</t-tooltip>
</div>
<p v-if="snapshot" class="snapshot-meta">
+ <AssistantActionButton v-if="snapshot.tools.length" :label="t('assistant.actions.toolExamples')"
+ :query="t('assistant.prompts.explainMcpTools', { id: serviceId })" :disabled="busy || refreshing" />
<span class="snapshot-meta__item">{{ t('mcpMetadata.toolCount', { count: snapshot.tools.length }) }}</span>
<span v-if="snapshot.server_name" class="snapshot-meta__item">{{ snapshot.server_name }} {{ snapshot.server_version }}</span>
<span class="snapshot-meta__item">{{ t('mcpMetadata.syncedAt') }}{{ formatTime(snapshot.synced_at) }}</span>
@@ -64,7 +66,13 @@
</div>
<t-loading :loading="busy" size="small" :text="busy ? t('mcpMetadata.fetching') : ''">
<div class="metadata-body">
- <p v-if="error" class="form-desc form-desc--error">{{ error }}</p>
+ <div v-if="error" class="metadata-error">
+ <p class="form-desc form-desc--error">{{ error }}</p>
+ <AssistantActionButton :label="t('assistant.actions.diagnose')"
+ :query="t('assistant.prompts.mcpFailure', { id: serviceId })"
+ :selection="{ field: t('mcpMetadata.tools'), text: error }"
+ :disabled="busy || disabled || policyBusy" />
+ </div>
<p v-else-if="snapshot?.stale" class="form-desc form-desc--warn">{{ t('mcpMetadata.stale') }}</p>
<p v-else-if="!busy && !snapshot" class="form-desc">{{ t('mcpMetadata.notSynced') }}</p>
<template v-if="snapshot">
@@ -81,6 +89,7 @@ import { useI18n } from 'vue-i18n'
import { getMCPMetadata, refreshMCPMetadata, type MCPMetadata } from '@/api/mcp-service'
import McpToolsList from './McpToolsList.vue'
import { useAssistantDataChange } from '@/utils/assistantDataChange'
+import AssistantActionButton from '@/components/assistant/AssistantActionButton.vue'
const props = defineProps<{ serviceId: string; disabled?: boolean }>()
const emit = defineEmits<{ (e: 'busy', value: boolean): void; (e: 'synced', value: boolean): void }>()
@@ -183,6 +192,13 @@ onBeforeUnmount(() => { generation++; emit('busy', false); emit('synced', false)
</script>
<style scoped lang="less">
+.metadata-error {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 8px;
+}
+
.metadata-heading {
display: flex;
align-items: center;
diff --git a/frontend/src/views/settings/components/McpServiceDialog.vue b/frontend/src/views/settings/components/McpServiceDialog.vue
index 285f89f7f..471a3f462 100644
--- a/frontend/src/views/settings/components/McpServiceDialog.vue
+++ b/frontend/src/views/settings/components/McpServiceDialog.vue
@@ -1,6 +1,7 @@
<template>
<SettingDrawer
:visible="dialogVisible"
+ :z-index="2300"
:title="mode === 'add' ? t('mcpServiceDialog.addTitle') : t('mcpServiceDialog.editTitle')"
class="mcp-drawer"
icon="tools"