feat: 添加全局人设与头像设置并优化对话及弹窗交互
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { beforeEach, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import ChatPersonaDialog from './ChatPersonaDialog.vue'
|
||||
import { useChatPreferences } from '@/stores/chatPreferences'
|
||||
|
||||
import { apiClient } from '@/services/apiClient'
|
||||
vi.mock('@/services/apiClient', () => ({apiClient:{get:vi.fn(),put:vi.fn()}}))
|
||||
beforeEach(() => { vi.mocked(apiClient.get).mockResolvedValue({version:0,name:'',system_prompt:'',dialogue_pairs:[]}); vi.mocked(apiClient.put).mockImplementation(async (_url, value) => ({...(value as object),version:1})); localStorage.removeItem('chat-persona-preferences-v1'); setActivePinia(createPinia()) })
|
||||
|
||||
it('saves global prompt and structured dialogue pairs to the AI Core', async () => {
|
||||
const wrapper = mount(ChatPersonaDialog)
|
||||
await flushPromises()
|
||||
await wrapper.get('.persona-prompt').setValue('耐心的老师')
|
||||
await wrapper.findAll('button').find(b => b.text().includes('添加对话对'))!.trigger('click')
|
||||
const inputs = wrapper.findAll('.dialogue-pairs textarea')
|
||||
await inputs[0]!.setValue('你好')
|
||||
await inputs[1]!.setValue('你好,我是老师')
|
||||
await wrapper.get('form').trigger('submit')
|
||||
await flushPromises()
|
||||
expect(apiClient.put).toHaveBeenCalledWith('/api/settings/persona', expect.objectContaining({system_prompt:'耐心的老师',dialogue_pairs:[{user:'你好',assistant:'你好,我是老师'}]}))
|
||||
expect(wrapper.emitted('close')).toHaveLength(1)
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('keeps unsaved edits out of active preferences', async () => {
|
||||
const wrapper = mount(ChatPersonaDialog)
|
||||
await flushPromises()
|
||||
await wrapper.findAll('textarea')[0]!.setValue('未保存人设')
|
||||
await wrapper.get('dialog').trigger('cancel')
|
||||
expect(useChatPreferences().settings.persona).toBe('')
|
||||
expect(wrapper.emitted('close')).toHaveLength(1)
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('persists separate local avatars and rejects remote avatar URLs', () => {
|
||||
const preferences = useChatPreferences()
|
||||
const aiAvatar = 'data:image/png;base64,aGVsbG8='
|
||||
const userAvatar = 'data:image/webp;base64,d29ybGQ='
|
||||
preferences.save({...preferences.settings,aiAvatar,userAvatar})
|
||||
setActivePinia(createPinia())
|
||||
expect(useChatPreferences().settings).toMatchObject({aiAvatar,userAvatar})
|
||||
expect(() => useChatPreferences().save({...preferences.settings,aiAvatar:'https://example.com/avatar.png'})).toThrow()
|
||||
expect(useChatPreferences().settings.aiAvatar).toBe(aiAvatar)
|
||||
})
|
||||
@@ -0,0 +1,122 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onBeforeUnmount, reactive, ref } from 'vue'
|
||||
import { useChatPreferences, validAvatar } from '@/stores/chatPreferences'
|
||||
import { t } from '@/i18n'
|
||||
import { apiClient } from '@/services/apiClient'
|
||||
interface GlobalPersona { version: number; name: string; system_prompt: string; dialogue_pairs: Array<{user:string;assistant:string}> }
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
const preferences = useChatPreferences()
|
||||
const draft = reactive({ ...preferences.settings })
|
||||
const error = ref('')
|
||||
const remote = reactive<GlobalPersona>({version:0,name:'',system_prompt:'',dialogue_pairs:[]})
|
||||
const ready = ref(false)
|
||||
const saving = ref(false)
|
||||
const loading = ref(0)
|
||||
const dialog = ref<HTMLDialogElement>()
|
||||
const previousFocus = document.activeElement as HTMLElement | null
|
||||
let active = true
|
||||
const generations = { aiAvatar: 0, userAvatar: 0 }
|
||||
async function loadGlobal() {
|
||||
error.value = ''; ready.value = false
|
||||
try { const result = await apiClient.get<GlobalPersona>('/api/settings/persona'); if (active) { Object.assign(remote,result); ready.value = true } }
|
||||
catch { if (active) error.value = t('无法加载全局人设,请重试。', 'Could not load global persona. Retry.') }
|
||||
}
|
||||
onMounted(() => { dialog.value?.showModal(); void loadGlobal() })
|
||||
onBeforeUnmount(() => { active = false; dialog.value?.close(); previousFocus?.focus() })
|
||||
async function chooseAvatar(event: Event, field: 'aiAvatar' | 'userAvatar') {
|
||||
const input = event.target as HTMLInputElement
|
||||
const file = input.files?.[0]
|
||||
input.value = ''
|
||||
if (!file) return
|
||||
const generation = ++generations[field]
|
||||
error.value = ''
|
||||
if (!['image/png','image/jpeg','image/webp'].includes(file.type) || file.size > 512 * 1024) {
|
||||
error.value = t('请选择不超过 512 KB 的 PNG、JPEG 或 WebP 图片。', 'Choose a PNG, JPEG or WebP image up to 512 KB.'); return
|
||||
}
|
||||
loading.value++
|
||||
try {
|
||||
const data = await new Promise<string>((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(String(reader.result)); reader.onerror = () => reject(new Error('read')); reader.readAsDataURL(file) })
|
||||
if (!validAvatar(data)) throw new Error('format')
|
||||
const image = new Image()
|
||||
image.src = data
|
||||
await image.decode()
|
||||
if (active && generation === generations[field]) draft[field] = data
|
||||
} catch { if (active && generation === generations[field]) error.value = t('图片无法读取,请重新选择。', 'Could not read the image. Choose another file.') }
|
||||
finally { loading.value-- }
|
||||
}
|
||||
function clearAvatar(field: 'aiAvatar' | 'userAvatar') { generations[field]++; draft[field] = '' }
|
||||
async function save() {
|
||||
if (loading.value || saving.value || !ready.value) return
|
||||
saving.value = true; error.value = ''
|
||||
try {
|
||||
const updated = await apiClient.put<GlobalPersona>('/api/settings/persona', JSON.parse(JSON.stringify(remote)))
|
||||
Object.assign(remote, updated)
|
||||
if (!active) return
|
||||
try { preferences.save({...draft,persona:'',presetDialogue:''}) }
|
||||
catch { error.value = t('全局人设已保存,但本机头像存储失败,请缩小图片后重试。', 'Global persona saved, but local avatars could not be saved. Reduce image sizes and retry.'); return }
|
||||
emit('close')
|
||||
} catch (reason) { if (active) error.value = reason instanceof Error ? reason.message : t('全局人设保存失败。', 'Could not save global persona.') }
|
||||
finally { saving.value = false }
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<dialog ref="dialog" class="modal persona-dialog" aria-labelledby="persona-title" @cancel.prevent="emit('close')" @click="($event.target === dialog) && emit('close')">
|
||||
<form @submit.prevent="save">
|
||||
<div class="persona-heading"><h2 id="persona-title">{{ t('人设与头像', 'Persona and avatars') }}</h2><button type="button" class="button-secondary" @click="emit('close')">{{ t('关闭', 'Close') }}</button></div>
|
||||
<p class="notice-banner">{{ t('全局人设 · 应用于连接此 AI Core 的所有对话与智能体。留空的提示词和对话示例不会拼入请求。', 'Global persona · Applies to all chats and agents connected to this AI Core. Empty prompts and examples are omitted.') }}</p>
|
||||
<p v-if="!ready" role="status">{{ t('正在加载全局设置', 'Loading global settings') }} <button type="button" class="button-secondary" @click="loadGlobal">{{ t('重试', 'Retry') }}</button></p>
|
||||
<fieldset :disabled="!ready || saving" class="persona-columns">
|
||||
<div class="persona-primary">
|
||||
<label class="field"><span>{{ t('人设名称', 'Persona name') }}</span><input v-model="remote.name" class="input" maxlength="128" :placeholder="t('例如:知识助理', 'For example: Knowledge assistant')" /></label>
|
||||
<label class="field"><span>{{ t('全局系统提示词', 'Global system prompt') }}</span><textarea v-model="remote.system_prompt" class="textarea persona-prompt" maxlength="16000" :placeholder="t('描述 AI 的身份、语气及回答要求;留空则不添加', 'Identity, tone and response requirements; leave blank to omit')" /></label>
|
||||
</div>
|
||||
<div class="persona-secondary">
|
||||
<details open class="ui-disclosure"><summary>{{ t('预设对话', 'Example dialogue') }}</summary>
|
||||
<div class="dialogue-pairs">
|
||||
<p class="subtle">{{ t('用成对对话示范回答风格,作为全局系统提示词的一部分。', 'Use dialogue pairs to demonstrate response style as part of the global system prompt.') }}</p>
|
||||
<article v-for="(pair,index) in remote.dialogue_pairs" :key="index" class="item-card">
|
||||
<label class="field"><span>{{ t('我', 'Me') }}</span><textarea v-model="pair.user" class="textarea" maxlength="8000" rows="2" /></label>
|
||||
<label class="field"><span>AI</span><textarea v-model="pair.assistant" class="textarea" maxlength="8000" rows="2" /></label>
|
||||
<button type="button" class="button-secondary" @click="remote.dialogue_pairs.splice(index,1)">{{ t('删除对话对', 'Remove pair') }}</button>
|
||||
</article>
|
||||
<button type="button" class="button-secondary" :disabled="remote.dialogue_pairs.length >= 20" @click="remote.dialogue_pairs.push({user:'',assistant:''})">+ {{ t('添加对话对', 'Add dialogue pair') }}</button>
|
||||
</div>
|
||||
</details>
|
||||
<h3>{{ t('本机头像', 'Local avatars') }}</h3>
|
||||
<div class="persona-avatars">
|
||||
<div v-for="field in (['aiAvatar', 'userAvatar'] as const)" :key="field" class="item-card avatar-setting">
|
||||
<strong>{{ field === 'aiAvatar' ? t('AI 头像', 'AI avatar') : t('我的头像', 'My avatar') }}</strong>
|
||||
<img v-if="draft[field]" :src="draft[field]" :alt="field === 'aiAvatar' ? 'AI' : t('我', 'Me')" /><span v-else class="avatar-placeholder">{{ field === 'aiAvatar' ? 'AI' : t('我', 'Me') }}</span>
|
||||
<label class="button-secondary avatar-upload">{{ t('选择图片', 'Choose image') }}<input type="file" accept="image/png,image/jpeg,image/webp" :aria-label="field === 'aiAvatar' ? t('选择 AI 头像', 'Choose AI avatar') : t('选择我的头像', 'Choose my avatar')" @change="chooseAvatar($event, field)" /></label>
|
||||
<button type="button" class="button-secondary" @click="clearAvatar(field)">{{ t('恢复默认', 'Reset') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<p v-if="error" class="error-banner" role="alert">{{ error }}</p>
|
||||
<div class="inline-actions persona-footer"><button class="button-primary" :disabled="loading > 0 || !ready || saving">{{ saving ? t('保存中…', 'Saving…') : loading ? t('读取图片中…', 'Reading image…') : t('保存', 'Save') }}</button><button type="button" class="button-secondary" @click="emit('close')">{{ t('取消', 'Cancel') }}</button></div>
|
||||
</form>
|
||||
</dialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.persona-dialog { width: min(1120px, calc(100vw - 32px)); max-height: calc(100dvh - 48px); box-sizing: border-box; margin: auto; overflow: auto; color: var(--color-text-primary); background: var(--color-surface-primary); }
|
||||
.persona-columns { display: grid; grid-template-columns: minmax(0,1fr) minmax(0,1fr); gap: 24px; border: 0; margin: 0; padding: 0; min-width: 0; }
|
||||
.persona-primary, .persona-secondary { min-width: 0; }
|
||||
.persona-prompt { min-height: 420px; }
|
||||
.dialogue-pairs { padding: 12px; display: grid; gap: 12px; max-height: 480px; overflow: auto; }
|
||||
.persona-footer { position: sticky; bottom: -24px; padding: 16px 0; background: var(--color-surface-primary); justify-content: flex-end; border-top: 1px solid var(--color-border-default); }
|
||||
@media (max-width: 760px) { .persona-columns { grid-template-columns: 1fr; } .persona-prompt { min-height: 240px; } }
|
||||
.persona-dialog::backdrop { background: var(--color-background-overlay); }
|
||||
.persona-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.persona-dialog .field { margin-block: 16px; }
|
||||
.persona-avatars { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; margin-block: 16px; }
|
||||
.avatar-setting { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; }
|
||||
.avatar-setting strong { width: 100%; }
|
||||
.avatar-setting img, .avatar-placeholder { width: 48px; height: 48px; border-radius: var(--radius-full); object-fit: cover; background: var(--color-accent-soft); display: grid; place-items: center; }
|
||||
.avatar-upload { position: relative; overflow: hidden; cursor: pointer; }
|
||||
.avatar-upload input { position: absolute; inset: 0; opacity: 0; width: 100%; cursor: pointer; }
|
||||
.avatar-upload:focus-within { outline: 2px solid var(--color-border-focus); }
|
||||
@media (max-width: 520px) { .persona-avatars { grid-template-columns: 1fr; } }
|
||||
</style>
|
||||
@@ -29,12 +29,23 @@ beforeEach(() => {
|
||||
vi.spyOn(useSkillStore(), 'loadSkills').mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('reuses the settings model cache and renders the shared select style', async () => {
|
||||
const providers = useProviderStore()
|
||||
providers.modelsByProvider.a = [{model_id:'a-default',name:'A model',capabilities:{chat:true}}]
|
||||
const wrapper = mount(ChatView)
|
||||
await flushPromises()
|
||||
expect(providers.loadModels).not.toHaveBeenCalled()
|
||||
expect(wrapper.get('select#chat-model-select').classes()).toContain('select')
|
||||
expect(wrapper.get('select#chat-model-select').text()).toContain('A model')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('preserves the selected provider and manual model after leaving and returning to chat', async () => {
|
||||
const chat = useChatStore()
|
||||
const first = mount(ChatView)
|
||||
await flushPromises()
|
||||
await first.get('select').setValue('b')
|
||||
await first.get('input[list="chat-models"]').setValue('b-manual')
|
||||
await first.get('input[data-field="manual-model"]').setValue('b-manual')
|
||||
first.unmount()
|
||||
const returned = mount(ChatView)
|
||||
await flushPromises()
|
||||
|
||||
@@ -7,8 +7,12 @@ import { useSkillStore } from '@/stores/skill'
|
||||
import MarkdownContent from '@/components/common/MarkdownContent.vue'
|
||||
import { useCitationNavigation } from '@/composables/useCitationNavigation'
|
||||
import { t } from '@/i18n'
|
||||
import ChatPersonaDialog from './ChatPersonaDialog.vue'
|
||||
import { useChatPreferences } from '@/stores/chatPreferences'
|
||||
|
||||
const chatStore = useChatStore()
|
||||
const preferences = useChatPreferences()
|
||||
const showPersona = ref(false)
|
||||
const providerStore = useProviderStore()
|
||||
const skillStore = useSkillStore()
|
||||
const { openCitation } = useCitationNavigation()
|
||||
@@ -36,7 +40,7 @@ onMounted(async () => {
|
||||
|
||||
async function refreshModels(providerId: string) {
|
||||
loadError.value = ''
|
||||
if (!providerId) return
|
||||
if (!providerId || providerStore.modelsByProvider[providerId] !== undefined) return
|
||||
try { await providerStore.loadModels(providerId) }
|
||||
catch (error) { if (!disposed && chatStore.selectedProviderId === providerId) loadError.value = error instanceof Error ? error.message : t('模型列表加载失败,请手动填写模型 ID。', 'Unable to load models. Enter a model ID manually.') }
|
||||
}
|
||||
@@ -69,7 +73,14 @@ async function openCitationCard(citation: Citation) {
|
||||
<div class="field compact"><label>Provider</label><select v-model="chatStore.selectedProviderId" class="select">
|
||||
<option v-for="provider in providerStore.enabledProviders" :key="provider.provider_id" :value="provider.provider_id">{{ provider.name }}</option>
|
||||
</select></div>
|
||||
<div class="field compact"><label>{{ t('模型 ID', 'Model ID') }}</label><input v-model="chatStore.selectedModel" class="input" list="chat-models" :placeholder="t('填写模型 ID', 'Enter model ID')" /><datalist id="chat-models"><option v-for="model in availableModels" :key="model.model_id" :value="model.model_id">{{ model.name }}</option></datalist></div>
|
||||
<div class="field compact"><label for="chat-model-select">{{ t('模型 ID', 'Model ID') }}</label>
|
||||
<select v-if="availableModels.length" id="chat-model-select" v-model="chatStore.selectedModel" class="select">
|
||||
<option v-if="!availableModels.some(m => m.model_id === chatStore.selectedModel)" :value="chatStore.selectedModel">{{ chatStore.selectedModel || t('选择模型', 'Select model') }}</option>
|
||||
<option v-for="model in availableModels" :key="model.model_id" :value="model.model_id">{{ model.name }}</option>
|
||||
</select>
|
||||
<input v-else id="chat-model-select" v-model="chatStore.selectedModel" class="input" data-field="manual-model" :placeholder="t('填写模型 ID', 'Enter model ID')" />
|
||||
</div>
|
||||
<button type="button" class="button-secondary" @click="showPersona = true">{{ t('人设与头像', 'Persona and avatars') }}</button>
|
||||
<label class="rag-toggle"><input v-model="chatStore.useRag" type="checkbox" :disabled="chatStore.isStreaming" />{{ t('检索知识库', 'Search knowledge base') }}</label>
|
||||
<span class="subtle">{{ t('开启后,将相关笔记片段发送给所选模型,并显示来源。技能调用请使用智能体。', 'When enabled, relevant note excerpts are sent to the selected model and citations are shown. Use Agent for skills.') }}</span>
|
||||
</header>
|
||||
@@ -78,9 +89,9 @@ async function openCitationCard(citation: Citation) {
|
||||
<main class="message-timeline">
|
||||
<div v-if="!chatStore.messages.length" class="empty-state"><div><strong>{{ t('开始一段知识对话', 'Start a knowledge conversation') }}</strong><p>{{ t('请先配置模型提供商。聊天记录保存在本地数据库中。', 'Configure a model provider first. Messages are saved in the local database.') }}</p></div></div>
|
||||
<article v-for="message in chatStore.messages" :key="message.message_id" class="message" :class="message.role">
|
||||
<div class="avatar">{{ message.role === 'user' ? t('你', 'You') : 'AI' }}</div>
|
||||
<div class="avatar"><img v-if="message.role === 'user' ? preferences.settings.userAvatar : preferences.settings.aiAvatar" :src="message.role === 'user' ? preferences.settings.userAvatar : preferences.settings.aiAvatar" :alt="message.role === 'user' ? t('我', 'Me') : 'AI'" /><span v-else>{{ message.role === 'user' ? t('你', 'You') : 'AI' }}</span></div>
|
||||
<div class="message-body">
|
||||
<details v-if="message.thinking" class="thinking"><summary>{{ t('思考过程', 'Reasoning') }}</summary><p>{{ message.thinking }}</p></details>
|
||||
<details v-if="message.thinking" class="thinking ui-disclosure"><summary>{{ t('思考过程', 'Reasoning') }}</summary><p>{{ message.thinking }}</p></details>
|
||||
<MarkdownContent v-if="message.content" class="message-content" :source="message.content" />
|
||||
<div v-else-if="chatStore.isStreaming" class="message-content">{{ t('正在思考…', 'Thinking…') }}</div>
|
||||
<div v-if="message.tool_calls?.length" class="tool-calls"><div v-for="call in message.tool_calls" :key="call.tool_call_id" class="item-card"><span class="badge info">{{ call.status }}</span><strong>{{ call.name }}</strong><pre>{{ JSON.stringify(call.parameters, null, 2) }}</pre></div></div>
|
||||
@@ -102,17 +113,19 @@ async function openCitationCard(citation: Citation) {
|
||||
<button v-else class="button-primary" :disabled="!chatStore.canSend || !chatStore.inputText.trim() || !chatStore.selectedProviderId || !chatStore.selectedModel.trim()" @click="send">{{ t('发送', 'Send') }}</button>
|
||||
</div>
|
||||
</footer>
|
||||
<ChatPersonaDialog v-if="showPersona" @close="showPersona = false" />
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.chat-page { display: grid; grid-template-rows: auto auto 1fr auto; height: 100%; min-height: 0; background: radial-gradient(circle at 85% -10%, var(--color-accent-soft), transparent 30%), var(--color-background-primary); }
|
||||
.chat-page { display: flex; flex-direction: column; height: 100%; min-height: 0; background: radial-gradient(circle at 85% -10%, var(--color-accent-soft), transparent 30%), var(--color-background-primary); }
|
||||
.chat-toolbar { display: flex; align-items: end; flex-wrap: wrap; gap: var(--space-md); padding: var(--space-md) var(--space-xl); border-bottom: 1px solid var(--color-border-default); background: var(--color-surface-secondary); box-shadow: var(--shadow-sm); z-index: 1; }
|
||||
.compact { min-width: 160px; }
|
||||
.rag-toggle { display: flex; align-items: center; gap: var(--space-xs); min-height: 36px; color: var(--color-text-secondary); }
|
||||
.chat-error { margin: var(--space-md) var(--space-xl) 0; }
|
||||
.message-timeline { min-height: 0; overflow: auto; padding: var(--space-xl) max(var(--space-xl), calc((100% - 820px) / 2)); user-select: text; }
|
||||
.message-timeline { flex: 1; min-height: 0; overflow: auto; padding: var(--space-xl) max(var(--space-xl), calc((100% - 820px) / 2)); user-select: text; }
|
||||
.message { display: grid; grid-template-columns: 36px 1fr; gap: var(--space-md); margin-bottom: var(--space-xl); animation: message-in var(--motion-normal) both; }
|
||||
.avatar img { width: 100%; height: 100%; object-fit: cover; border-radius: inherit; }
|
||||
.avatar { display: grid; place-items: center; width: 34px; height: 34px; border: 1px solid var(--color-border-default); border-radius: var(--radius-full); background: var(--color-background-tertiary); box-shadow: var(--shadow-sm); font-weight: 700; }
|
||||
.assistant .avatar { background: var(--color-accent-soft); color: var(--color-accent-primary); }
|
||||
.message-body { min-width: 0; padding: var(--space-md) var(--space-lg); border: 1px solid var(--color-border-subtle); border-radius: 4px var(--radius-lg) var(--radius-lg) var(--radius-lg); background: color-mix(in srgb, var(--color-surface-primary) 88%, transparent); box-shadow: var(--shadow-sm); }
|
||||
@@ -126,7 +139,7 @@ async function openCitationCard(citation: Citation) {
|
||||
.citation-card { display: flex; align-items: flex-start; gap: var(--space-sm); padding: var(--space-md); border: 1px solid var(--color-border-default); border-radius: var(--radius-md); background: var(--color-surface-primary); text-align: left; transition: border-color var(--motion-fast), transform var(--motion-fast), box-shadow var(--motion-fast); }
|
||||
.citation-card:hover { border-color: var(--color-accent-secondary); transform: translateY(-1px); box-shadow: var(--shadow-sm); }
|
||||
.citation-card small { display: block; margin-top: 2px; color: var(--color-text-secondary); }
|
||||
.composer { padding: var(--space-md) max(var(--space-xl), calc((100% - 820px) / 2)); border-top: 1px solid var(--color-border-default); background: var(--color-surface-secondary); box-shadow: 0 -8px 24px color-mix(in srgb, var(--color-text-primary) 5%, transparent); }
|
||||
.composer { flex-shrink: 0; padding: var(--space-md) max(var(--space-xl), calc((100% - 820px) / 2)); border-top: 1px solid var(--color-border-default); background: var(--color-surface-secondary); box-shadow: 0 -8px 24px color-mix(in srgb, var(--color-text-primary) 5%, transparent); }
|
||||
.composer .textarea { min-height: 72px; }
|
||||
.composer-actions { display: flex; align-items: center; justify-content: space-between; gap: var(--space-md); margin-top: var(--space-sm); }
|
||||
|
||||
|
||||
@@ -33,6 +33,18 @@ beforeEach(() => {
|
||||
afterEach(() => { wrappers.splice(0).forEach(wrapper => wrapper.unmount()) })
|
||||
|
||||
describe('ProviderForm', () => {
|
||||
it('uses a top-layer dialog and restores the underlying scroll container', async () => {
|
||||
const host = document.createElement('div')
|
||||
host.style.overflow = 'auto'
|
||||
document.body.appendChild(host)
|
||||
const wrapper = mount(ProviderForm, {attachTo:host})
|
||||
await flushPromises()
|
||||
expect(wrapper.get('dialog').element.open).toBe(true)
|
||||
expect(host.style.overflow).toBe('hidden')
|
||||
wrapper.unmount()
|
||||
expect(host.style.overflow).toBe('auto')
|
||||
host.remove()
|
||||
})
|
||||
it('saves model-scoped context settings and restores them on edit', async () => {
|
||||
const policy = {model:'old-model',context_window:65536,output_reserve:8192,threshold:0.8,mode:'detect' as const,prompt:'保留已确认事实'}
|
||||
const wrapper = await render({...existing,context_policies:[policy]})
|
||||
|
||||
@@ -67,6 +67,8 @@ async function probeRequest() {
|
||||
}
|
||||
const contextChanged = ref(false)
|
||||
const dialog = ref<HTMLElement>()
|
||||
const backdrop = ref<HTMLDialogElement>()
|
||||
const scrollLocks: Array<{element: HTMLElement; overflow: string}> = []
|
||||
const previousFocus = document.activeElement as HTMLElement | null
|
||||
let active = true
|
||||
let credentialGeneration = 0
|
||||
@@ -84,6 +86,11 @@ async function loadPresets() {
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
backdrop.value?.showModal()
|
||||
for (let element = backdrop.value?.parentElement; element; element = element.parentElement) {
|
||||
scrollLocks.push({element, overflow: element.style.overflow})
|
||||
element.style.overflow = 'hidden'
|
||||
}
|
||||
void loadPresets()
|
||||
if (props.provider?.credential_id) {
|
||||
const generation = credentialGeneration
|
||||
@@ -134,6 +141,8 @@ function close() {
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
backdrop.value?.close()
|
||||
for (const lock of scrollLocks) lock.element.style.overflow = lock.overflow
|
||||
active = false
|
||||
apiKey.value = ''
|
||||
previousFocus?.focus()
|
||||
@@ -182,7 +191,7 @@ async function save() {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="modal-backdrop provider-backdrop" @click.self="close" @keydown="handleKeydown">
|
||||
<dialog ref="backdrop" class="provider-backdrop" @click.self="close" @keydown="handleKeydown" @cancel.prevent="close">
|
||||
<div ref="dialog" class="modal provider-modal" role="dialog" aria-modal="true" aria-labelledby="provider-form-title" :aria-busy="saving">
|
||||
<div class="form-heading"><h2 id="provider-form-title">{{ provider ? t('编辑 Provider', 'Edit Provider') : t('新增 Provider', 'Add Provider') }}</h2><button type="button" class="button-secondary" :aria-label="t('关闭提供商表单', 'Close provider form')" @click="close">{{ t('关闭', 'Close') }}</button></div>
|
||||
<p v-if="presetsLoading" class="subtle" role="status">{{ t('正在加载提供商预设…', 'Loading provider presets…') }}</p>
|
||||
@@ -213,10 +222,14 @@ async function save() {
|
||||
<div class="inline-actions form-footer"><button class="button-primary" type="submit" :disabled="saving || credentialLoading">{{ saving ? t('保存中…', 'Saving…') : t('保存提供商', 'Save provider') }}</button><button type="button" class="button-secondary" @click="close">{{ t('取消', 'Cancel') }}</button></div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</dialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.provider-backdrop { position: fixed; inset: 0; width: 100%; height: 100%; max-width: none; max-height: none; margin: 0; padding: 24px; border: 0; box-sizing: border-box; background: transparent; overflow: hidden; overscroll-behavior: contain; }
|
||||
.provider-backdrop[open] { display: grid; place-items: center; }
|
||||
.provider-backdrop::backdrop { background: var(--color-background-overlay); }
|
||||
.provider-modal { overflow-y: auto; overscroll-behavior: contain; }
|
||||
.provider-modal { width: min(820px, 100%); max-height: 90dvh; }
|
||||
.form-heading { display: flex; align-items: center; justify-content: space-between; gap: var(--space-md); margin-bottom: var(--space-md); }
|
||||
.form-heading h2 { margin: 0; }
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import type { ProviderConfig } from '@/contracts'
|
||||
import ProviderForm from './ProviderForm.vue'
|
||||
import ChatPersonaDialog from '@/features/chat/ChatPersonaDialog.vue'
|
||||
import ProviderLogo from './ProviderLogo.vue'
|
||||
import ModelRoutingSettings from './ModelRoutingSettings.vue'
|
||||
import LocalModelSettings from './LocalModelSettings.vue'
|
||||
@@ -17,6 +18,7 @@ const sections = computed<Array<{ id: Section; label: string }>>(() => [
|
||||
{ id: 'index', label: t('索引与模型', 'Index and Models') }, { id: 'permissions', label: t('权限', 'Permissions') }, { id: 'ai-core', label: t('AI Core 诊断', 'AI Core Diagnostics') },
|
||||
])
|
||||
const activeSection = ref<Section>('general')
|
||||
const showPersona = ref(false)
|
||||
const settingsStore = useSettingsStore()
|
||||
const providerStore = useProviderStore()
|
||||
const themeStore = useThemeStore()
|
||||
@@ -75,6 +77,8 @@ async function chooseDefaultModel(provider: ProviderConfig, event: Event) {
|
||||
<header class="feature-header"><div><h1>{{ t('设置', 'Settings') }}</h1><p>{{ t('管理应用偏好、模型、索引、权限和本地 AI Core。', 'Manage application preferences, models, indexing, permissions, and the local AI Core.') }}</p></div></header>
|
||||
<nav class="settings-nav"><button v-for="section in sections" :key="section.id" :class="{ active: activeSection === section.id }" @click="activeSection = section.id">{{ section.label }}</button></nav>
|
||||
|
||||
<section v-if="activeSection === 'general'" class="panel settings-section"><div class="setting-row"><span><strong>{{ t('全局人设', 'Global persona') }}</strong><small>{{ t('统一设置所有 AI 对话和智能体的系统人设与对话示例', 'System persona and examples for all AI chats and agents') }}</small></span><button class="button-secondary" @click="showPersona = true">{{ t('编辑人设与头像', 'Edit persona and avatars') }}</button></div></section>
|
||||
<ChatPersonaDialog v-if="showPersona" @close="showPersona = false" />
|
||||
<div v-if="activeSection === 'general'" class="panel settings-section"><h2>{{ t('通用', 'General') }}</h2><label class="setting-row"><span><strong>{{ t('恢复上次 Vault', 'Restore last Vault') }}</strong><small>{{ t('启动后自动打开最近使用的知识库', 'Open the most recently used knowledge base at startup') }}</small></span><input v-model="settingsStore.restoreLastVault" type="checkbox" /></label><div class="setting-row"><span><strong>{{ t('自动保存间隔', 'Autosave interval') }}</strong><small>{{ t('编辑停止后等待多久写入文件', 'How long to wait after editing before saving') }}</small></span><select v-model.number="settingsStore.autoSaveInterval" class="select short"><option :value="500">0.5 {{ t('秒', 'sec') }}</option><option :value="1500">1.5 {{ t('秒', 'sec') }}</option><option :value="3000">3 {{ t('秒', 'sec') }}</option></select></div><div class="setting-row"><span><strong>{{ t('界面语言', 'Interface language') }}</strong><small>{{ t('切换后立即应用到界面', 'Applied to the interface immediately') }}</small></span><select v-model="settingsStore.language" class="select short"><option value="zh-CN">简体中文</option><option value="en">English</option></select></div><div class="setting-row"><span><strong>{{ t('版本', 'Version') }}</strong><small>Desktop / AI Core</small></span><span>{{ settingsStore.appVersion }} / {{ settingsStore.aiCoreVersion }}</span></div></div>
|
||||
|
||||
<div v-else-if="activeSection === 'editor'" class="panel settings-section"><h2>{{ t('编辑器', 'Editor') }}</h2><div class="setting-row"><span><strong>{{ t('默认模式', 'Default mode') }}</strong><small>{{ t('新打开文件使用的编辑器模式', 'Editor mode used for newly opened files') }}</small></span><select v-model="settingsStore.defaultEditorMode" class="select short"><option value="wysiwyg">{{ t('写作与预览', 'Writing and preview') }}</option><option value="source">{{ t('Markdown 源码', 'Markdown source') }}</option></select></div><div class="setting-row"><span><strong>{{ t('字号', 'Font size') }}</strong></span><input v-model.number="themeStore.fontEditorSize" class="input short" type="number" min="12" max="32" /></div><div class="setting-row"><span><strong>{{ t('行高', 'Line height') }}</strong></span><input v-model.number="themeStore.lineHeight" class="input short" type="number" min="1.2" max="2.4" step="0.1" /></div><div class="setting-row"><span><strong>{{ t('行宽', 'Line width') }}</strong><small>{{ t('Markdown 预览最大字符宽度', 'Maximum character width for Markdown preview') }}</small></span><input v-model.number="settingsStore.editorLineWidth" class="input short" type="number" min="40" max="140" /></div><label class="setting-row"><span><strong>{{ t('拼写检查', 'Spell check') }}</strong><small>{{ t('在写作与源码编辑器中使用系统拼写检查', 'Use system spell checking in visual and source editors') }}</small></span><input v-model="settingsStore.spellCheck" type="checkbox" /></label></div>
|
||||
|
||||
@@ -21,7 +21,7 @@ it('distinguishes unreported tokens from zero and switches to request counts', a
|
||||
})
|
||||
|
||||
|
||||
it('stacks models inside the source column and keeps their shades distinct', () => {
|
||||
it('shades by consumed metric and gives equal usage equal shades', async () => {
|
||||
const models = [100, 200].map((count, index) => ({ key: `m${index}`, provider_id: 'p', model: `model-${index}`, requests: 1, totals: { input_tokens: count }, coverage: { input_tokens: 1 } }))
|
||||
const wrapper = mount(UsageChart, { props: { buckets: [{ date: '2026-09-05', end_date: '2026-09-05', local: { requests: 0, totals: {}, coverage: {} }, api: { requests: 2, totals: { input_tokens: 300 }, coverage: { input_tokens: 2 }, models } }] } })
|
||||
const segments = wrapper.findAll('.model-segment')
|
||||
@@ -29,5 +29,11 @@ it('stacks models inside the source column and keeps their shades distinct', ()
|
||||
expect(segments[0]!.attributes('style')).not.toBe(segments[1]!.attributes('style'))
|
||||
expect(wrapper.get('.model-legend').text()).toContain('model-1')
|
||||
expect(segments[0]!.attributes('title')).toContain('100')
|
||||
// happy-dom drops color-mix declarations; inspect the bound color values.
|
||||
const colors = wrapper.vm as unknown as {modelColor:(key:string,source:'api') => string}
|
||||
expect(colors.modelColor('m0','api')).toContain('67.5%')
|
||||
expect(colors.modelColor('m1','api')).toContain('95%')
|
||||
await wrapper.get('select').setValue('requests')
|
||||
expect(colors.modelColor('m0','api')).toBe(colors.modelColor('m1','api'))
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
@@ -25,9 +25,13 @@ function value(bucket: UsageBucket, source: 'local' | 'api') {
|
||||
return metric.value === 'requests' ? item.requests : item.requests === 0 ? 0 : item.totals[metric.value] ?? null
|
||||
}
|
||||
const modelLegend = computed(() => sources.flatMap(source => {
|
||||
const entries = new Map<string, ModelUsage>()
|
||||
for (const bucket of props.buckets) for (const item of bucket[source].models ?? []) entries.set(item.key, item)
|
||||
return [...entries.values()].sort((a, b) => a.key.localeCompare(b.key)).map((item, index, all) => ({ ...item, source, shade: all.length === 1 ? 85 : 40 + index / (all.length - 1) * 55 }))
|
||||
const entries = new Map<string, ModelUsage & { consumed: number }>()
|
||||
for (const bucket of props.buckets) for (const item of bucket[source].models ?? []) {
|
||||
const previous = entries.get(item.key)
|
||||
entries.set(item.key, {...item, consumed: (previous?.consumed ?? 0) + modelValue(item)})
|
||||
}
|
||||
const peak = Math.max(1, ...[...entries.values()].map(item => item.consumed))
|
||||
return [...entries.values()].sort((a, b) => b.consumed - a.consumed || a.key.localeCompare(b.key)).map(item => ({ ...item, source, shade: 40 + item.consumed / peak * 55 }))
|
||||
}))
|
||||
function modelColor(key: string, source: 'local' | 'api') {
|
||||
const shade = modelLegend.value.find(item => item.key === key && item.source === source)?.shade ?? 85
|
||||
@@ -76,6 +80,7 @@ const maximum = computed(() => Math.max(1, ...props.buckets.flatMap(bucket => so
|
||||
<div v-for="item in sums" :key="item.source" class="pie-value" :class="item.source"><AppIcon :icon="item.source === 'local' ? Cpu : Connection" :size="16" /><span>{{ labels[item.source] }}</span><strong>{{ item.coverage ? item.value.toLocaleString() : item.requests ? t('未提供', 'Unavailable') : '0' }} · {{ total ? (item.value / total * 100).toFixed(1) + '%' : '—' }}</strong><small>{{ t('覆盖', 'Coverage') }} {{ item.coverage }}/{{ item.requests }}</small></div>
|
||||
<p class="subtle">{{ t('占比仅基于已报告值;缺失指标不计入分母。', 'Shares use reported values only; missing counters are excluded.') }}</p>
|
||||
</aside></div>
|
||||
<p v-if="modelLegend.length" class="subtle">{{ t('同一来源内,颜色越深表示所选时段该模型的累计消耗越多。', 'Within each source, darker shades indicate greater model usage over the selected period.') }}</p>
|
||||
<div class="model-legend"><span v-for="item in modelLegend" :key="`${item.source}:${item.key}`" :title="item.provider_id"><i :style="{ background: modelColor(item.key, item.source) }" />{{ item.model }}</span></div>
|
||||
<p class="subtle">{{ t('按本机时区分组;柱高仅汇总已报告值,悬停可查看覆盖请求数。虚线表示有请求但未提供该指标,不作为零消耗。', 'Grouped by your local UTC offset. Bars sum reported values; hover for coverage. Dashed markers mean requests with unavailable counters, not zero usage.') }}</p>
|
||||
<details class="ui-disclosure"><summary>{{ t('查看图表数据', 'View chart data') }}</summary><div class="chart-scroll"><table><thead><tr><th>{{ t('日期', 'Date') }}</th><th>{{ labels.local }}</th><th>{{ labels.api }}</th></tr></thead><tbody><tr v-for="bucket in buckets" :key="bucket.date"><th>{{ bucket.date }}<template v-if="bucket.date !== bucket.end_date"> – {{ bucket.end_date }}</template></th><td v-for="source in sources" :key="source">{{ description(bucket, source) }}</td></tr></tbody></table></div></details>
|
||||
|
||||
Reference in New Issue
Block a user