feat: complete grounded digital avatar chat experience
This commit is contained in:
@@ -1,40 +1,69 @@
|
||||
<template>
|
||||
<div class="chat-page">
|
||||
<header class="chat-header">
|
||||
<button class="back-btn" @click="router.back()">‹</button>
|
||||
<button v-if="!isPublic" class="back-btn" @click="router.back()">‹</button>
|
||||
<div class="avatar-heading">
|
||||
<div class="avatar-mark">{{ avatar?.emoji || '🤖' }}</div>
|
||||
<div class="avatar-mark">
|
||||
<img v-if="avatar?.photoUrl" :src="avatar.photoUrl" alt="" referrerpolicy="no-referrer" />
|
||||
<span v-else>{{ avatar?.emoji || '🤖' }}</span>
|
||||
</div>
|
||||
<div>
|
||||
<h1>{{ avatar?.displayName || avatar?.name || '数字分身' }}</h1>
|
||||
<span class="online-state">● 随时可以和我聊聊</span>
|
||||
<span class="online-state" :class="avatarStatus.tone"><i></i>{{ avatarStatus.label }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button class="settings-btn" title="编辑分身" @click="router.push(`/avatar/edit/${avatarId}`)">⚙</button>
|
||||
<button v-if="!isPublic" class="settings-btn" title="编辑分身" @click="router.push(`/avatar/edit/${avatarId}`)">⚙</button>
|
||||
</header>
|
||||
|
||||
<main ref="messageList" class="message-list">
|
||||
<div v-if="!messages.length" class="welcome-card">
|
||||
<div class="welcome-icon">✦</div>
|
||||
<h2>你好,我是{{ avatar?.displayName || '你的数字分身' }}</h2>
|
||||
<p>我会优先参考标准问答和知识库,再结合自己的理解回答你。</p>
|
||||
<div class="starter-list">
|
||||
<button v-for="starter in starters" :key="starter" @click="sendMessage(starter)">{{ starter }}</button>
|
||||
<div class="welcome-avatar">
|
||||
<img v-if="avatar?.photoUrl" :src="avatar.photoUrl" alt="" referrerpolicy="no-referrer" />
|
||||
<span v-else>{{ avatar?.emoji || '🤖' }}</span>
|
||||
</div>
|
||||
<h2>有什么想聊的?</h2>
|
||||
<p class="welcome-description">{{ avatar?.description || '很高兴和你聊聊。' }}</p>
|
||||
</div>
|
||||
|
||||
<article v-for="(message, index) in messages" :key="`${message.role}-${index}`" class="message-row" :class="message.role">
|
||||
<div v-if="message.role === 'assistant'" class="message-avatar">{{ avatar?.emoji || '🤖' }}</div>
|
||||
<div v-if="message.role === 'assistant'" class="message-avatar avatar-message-face">
|
||||
<img v-if="avatar?.photoUrl" :src="avatar.photoUrl" alt="" referrerpolicy="no-referrer" />
|
||||
<span v-else>{{ avatar?.emoji || '🤖' }}</span>
|
||||
</div>
|
||||
<div class="message-column">
|
||||
<div class="message-bubble">{{ message.content }}</div>
|
||||
<div class="message-bubble" :class="{ streaming: sending && message.role === 'assistant' && index === messages.length - 1 }">
|
||||
<template v-if="message.role === 'assistant'">
|
||||
<span
|
||||
v-for="character in renderChatMarkdownCharacters(message.characters?.length ? message.characters : message.content)"
|
||||
:key="character.key"
|
||||
class="typing-character"
|
||||
:class="{
|
||||
newline: character.newline,
|
||||
'markdown-bold': character.bold,
|
||||
'markdown-italic': character.italic,
|
||||
'markdown-code': character.code,
|
||||
'markdown-heading': character.heading
|
||||
}"
|
||||
>{{ character.text }}</span>
|
||||
</template>
|
||||
<template v-else>{{ message.content }}</template>
|
||||
</div>
|
||||
<div v-if="message.source || message.references?.length" class="message-source">
|
||||
{{ sourceLabel(message.source) }}
|
||||
<span v-if="message.references?.length"> · {{ message.references.map((item) => item.filename).filter(Boolean).join('、') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="message.role === 'user'" class="message-avatar user-message-face">
|
||||
<img v-if="userAvatarUrl" :src="userAvatarUrl" alt="" referrerpolicy="no-referrer" />
|
||||
<span v-else>{{ userAvatarInitial }}</span>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<div v-if="sending" class="message-row assistant">
|
||||
<div class="message-avatar">{{ avatar?.emoji || '🤖' }}</div>
|
||||
<div v-if="thinking" class="message-row assistant">
|
||||
<div class="message-avatar avatar-message-face">
|
||||
<img v-if="avatar?.photoUrl" :src="avatar.photoUrl" alt="" referrerpolicy="no-referrer" />
|
||||
<span v-else>{{ avatar?.emoji || '🤖' }}</span>
|
||||
</div>
|
||||
<div class="message-bubble typing"><i></i><i></i><i></i></div>
|
||||
</div>
|
||||
<p v-if="errorMessage" class="chat-error">{{ errorMessage }} <button @click="retryLast">重试</button></p>
|
||||
@@ -48,33 +77,50 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onMounted, ref } from 'vue'
|
||||
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { getAvatarDetail, sendAvatarChat, type ChatMessage } from '@/api'
|
||||
import { getAvatarDetail, getPublicAvatar, streamAvatarChat, streamPublicAvatarChat, type ChatMessage } from '@/api'
|
||||
import { useAvatarStore } from '@/store/avatar'
|
||||
import { useUserStore } from '@/store/user'
|
||||
import { renderChatMarkdownCharacters } from '@/utils/chat-markdown.js'
|
||||
|
||||
type DisplayMessage = ChatMessage & {
|
||||
source?: 'qa' | 'knowledge' | 'qwen'
|
||||
source?: 'qa' | 'knowledge' | 'qwen' | 'public'
|
||||
references?: Array<{ filename?: string }>
|
||||
characters?: string[]
|
||||
}
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const store = useAvatarStore()
|
||||
const avatarId = String(route.params.id || '')
|
||||
const userStore = useUserStore()
|
||||
const shareToken = String(route.params.shareToken || '')
|
||||
const isPublic = Boolean(shareToken)
|
||||
const avatarId = ref(String(route.params.id || ''))
|
||||
const avatar = ref<any>(null)
|
||||
const messages = ref<DisplayMessage[]>([])
|
||||
const inputText = ref('')
|
||||
const sending = ref(false)
|
||||
const thinking = ref(false)
|
||||
const errorMessage = ref('')
|
||||
const lastQuestion = ref('')
|
||||
const messageList = ref<HTMLElement | null>(null)
|
||||
const starters = ['介绍一下你自己', '你能帮我做什么?', '请根据我的知识库回答一个问题']
|
||||
let scrollFrame: number | null = null
|
||||
|
||||
const userAvatarUrl = computed(() => userStore.user?.avatarUrl || store.userProfile?.avatarUrl || '')
|
||||
const userAvatarInitial = computed(() => (userStore.user?.nickname || store.userProfile?.nickname || '我').trim().slice(0, 1))
|
||||
const avatarStatus = computed(() => {
|
||||
const status = avatar.value?.status || 'active'
|
||||
if (status === 'inactive') return { tone: 'inactive', label: '当前已停用' }
|
||||
if (status === 'training') return { tone: 'training', label: '知识训练中' }
|
||||
return { tone: 'active', label: '在线,随时可以和我聊聊' }
|
||||
})
|
||||
|
||||
const sourceLabel = (source?: DisplayMessage['source']) => ({
|
||||
qa: '标准问答对',
|
||||
knowledge: '参考文件知识库',
|
||||
qwen: 'Qwen 智能回答'
|
||||
qwen: '智能回答',
|
||||
public: ''
|
||||
}[source || ''] || '')
|
||||
|
||||
const scrollToBottom = async () => {
|
||||
@@ -82,9 +128,89 @@ const scrollToBottom = async () => {
|
||||
if (messageList.value) messageList.value.scrollTop = messageList.value.scrollHeight
|
||||
}
|
||||
|
||||
const scrollDuringStream = () => {
|
||||
if (scrollFrame !== null) return
|
||||
scrollFrame = window.requestAnimationFrame(() => {
|
||||
if (messageList.value) messageList.value.scrollTop = messageList.value.scrollHeight
|
||||
scrollFrame = null
|
||||
})
|
||||
}
|
||||
|
||||
const sleep = (delay: number) => new Promise<void>((resolve) => window.setTimeout(resolve, delay))
|
||||
|
||||
const createStreamReply = () => {
|
||||
const reply = reactive<DisplayMessage>({
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
characters: []
|
||||
})
|
||||
let attached = false
|
||||
const attach = () => {
|
||||
if (attached) return
|
||||
messages.value.push(reply)
|
||||
attached = true
|
||||
}
|
||||
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches
|
||||
const queue: string[] = []
|
||||
let draining: Promise<void> | null = null
|
||||
|
||||
const drain = async () => {
|
||||
while (queue.length) {
|
||||
let character = queue.shift() || ''
|
||||
if (character === '\r') continue
|
||||
if (/\s/.test(character) && character !== '\n') character = ' '
|
||||
const previous = reply.characters?.[reply.characters.length - 1] || ''
|
||||
if (character === ' ' && (!previous || previous === ' ' || previous === '\n')) continue
|
||||
if (character === '\n') {
|
||||
while (reply.characters?.[reply.characters.length - 1] === ' ') {
|
||||
reply.characters.pop()
|
||||
reply.content = reply.content.slice(0, -1)
|
||||
}
|
||||
if (!reply.characters?.length || reply.characters[reply.characters.length - 1] === '\n') continue
|
||||
}
|
||||
reply.content += character
|
||||
reply.characters?.push(character)
|
||||
scrollDuringStream()
|
||||
await sleep(/[,。!?;:\n]/.test(character) ? 140 : 28)
|
||||
}
|
||||
draining = null
|
||||
}
|
||||
|
||||
return {
|
||||
reply,
|
||||
append: (content: string) => {
|
||||
if (!content) return
|
||||
attach()
|
||||
if (reduceMotion) {
|
||||
reply.content += content
|
||||
void scrollToBottom()
|
||||
return
|
||||
}
|
||||
queue.push(...Array.from(content))
|
||||
if (!draining) draining = drain()
|
||||
},
|
||||
finish: async () => {
|
||||
if (draining) await draining
|
||||
while (reply.characters?.length && /[\s\n]/.test(reply.characters[reply.characters.length - 1])) {
|
||||
reply.characters.pop()
|
||||
reply.content = reply.content.slice(0, -1)
|
||||
}
|
||||
if (reduceMotion) reply.characters = []
|
||||
if (attached) await scrollToBottom()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const loadAvatar = async () => {
|
||||
avatar.value = store.avatars.find((item) => String(item.id) === avatarId)
|
||||
if (!avatar.value) avatar.value = await getAvatarDetail(avatarId)
|
||||
if (isPublic) {
|
||||
avatar.value = await getPublicAvatar(shareToken)
|
||||
avatarId.value = String(avatar.value?.id || '')
|
||||
document.title = avatar.value?.displayName || avatar.value?.name || '会会数字分身'
|
||||
return
|
||||
}
|
||||
avatar.value = store.avatars.find((item) => String(item.id) === avatarId.value)
|
||||
if (!avatar.value) avatar.value = await getAvatarDetail(avatarId.value)
|
||||
document.title = avatar.value?.displayName || avatar.value?.name || '会会数字分身'
|
||||
}
|
||||
|
||||
const sendMessage = async (value: string) => {
|
||||
@@ -95,17 +221,35 @@ const sendMessage = async (value: string) => {
|
||||
errorMessage.value = ''
|
||||
messages.value.push({ role: 'user', content: question })
|
||||
sending.value = true
|
||||
thinking.value = true
|
||||
await scrollToBottom()
|
||||
try {
|
||||
const response = await sendAvatarChat(avatarId, {
|
||||
const payload = {
|
||||
message: question,
|
||||
history: messages.value.slice(-10).map(({ role, content }) => ({ role, content }))
|
||||
})
|
||||
messages.value.push({ role: 'assistant', content: response.answer, source: response.source, references: response.references })
|
||||
await scrollToBottom()
|
||||
}
|
||||
const streamed = createStreamReply()
|
||||
const handlers = {
|
||||
onMeta: (meta: Pick<DisplayMessage, 'source' | 'references'>) => {
|
||||
streamed.reply.source = meta.source
|
||||
streamed.reply.references = meta.references
|
||||
},
|
||||
onDelta: (content: string) => {
|
||||
thinking.value = false
|
||||
streamed.append(content)
|
||||
}
|
||||
}
|
||||
if (isPublic) {
|
||||
await streamPublicAvatarChat(shareToken, payload, handlers)
|
||||
} else {
|
||||
await streamAvatarChat(avatarId.value, payload, handlers)
|
||||
}
|
||||
thinking.value = false
|
||||
await streamed.finish()
|
||||
} catch (error: any) {
|
||||
errorMessage.value = error?.message || '暂时无法回答,请稍后重试'
|
||||
} finally {
|
||||
thinking.value = false
|
||||
sending.value = false
|
||||
}
|
||||
}
|
||||
@@ -121,32 +265,37 @@ onMounted(loadAvatar)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.chat-page { min-height: 100dvh; display: flex; flex-direction: column; background: #FFF8F1; color: #3B2417; }
|
||||
.chat-header { flex: 0 0 auto; display: flex; align-items: center; gap: 12px; padding: 14px 18px; color: white; background: linear-gradient(135deg, #F97316, #FB923C); box-shadow: 0 5px 18px rgba(249, 115, 22, .2); }
|
||||
.chat-page { height: 100dvh; min-height: 0; display: flex; flex-direction: column; overflow: hidden; background: #FFF8F1; color: #3B2417; }
|
||||
.chat-header { position: sticky; top: 0; z-index: 10; flex: 0 0 auto; display: flex; align-items: center; gap: 12px; padding: 14px 18px; color: white; background: linear-gradient(135deg, #F97316, #FB923C); box-shadow: 0 5px 18px rgba(249, 115, 22, .2); }
|
||||
.back-btn, .settings-btn { border: 0; background: transparent; color: white; cursor: pointer; font-size: 25px; padding: 2px 6px; }
|
||||
.settings-btn { font-size: 20px; margin-left: auto; }
|
||||
.avatar-heading { display: flex; align-items: center; gap: 10px; }
|
||||
.avatar-mark { width: 38px; height: 38px; display: grid; place-items: center; border-radius: 13px; background: rgba(255,255,255,.24); font-size: 23px; }
|
||||
.avatar-mark { width: 38px; height: 38px; display: grid; place-items: center; overflow: hidden; border-radius: 13px; background: rgba(255,255,255,.24); font-size: 23px; }.avatar-mark img { width: 100%; height: 100%; object-fit: cover; }
|
||||
.avatar-heading h1 { margin: 0; font-size: 17px; }
|
||||
.online-state { display: block; margin-top: 3px; font-size: 11px; opacity: .86; }
|
||||
.message-list { flex: 1 1 auto; width: min(760px, 100%); box-sizing: border-box; margin: 0 auto; padding: 24px 18px 120px; overflow-y: auto; }
|
||||
.online-state { display: flex; align-items: center; gap: 4px; margin-top: 3px; font-size: 11px; opacity: .9; }.online-state i { width: 7px; height: 7px; border-radius: 50%; background: #86EFAC; box-shadow: 0 0 0 2px rgba(255,255,255,.22); }.online-state.training i { background: #FDE68A; }.online-state.inactive i { background: #FDA4AF; }
|
||||
.message-list { min-height: 0; flex: 1 1 auto; width: min(760px, 100%); box-sizing: border-box; margin: 0 auto; padding: 24px 18px 120px; overflow-y: auto; overscroll-behavior: contain; }
|
||||
.welcome-card { padding: 28px 20px; text-align: center; background: rgba(255,255,255,.72); border: 1px solid #FFE1C2; border-radius: 22px; box-shadow: 0 10px 28px rgba(181, 99, 35, .08); }
|
||||
.welcome-icon { color: #F97316; font-size: 30px; }
|
||||
.welcome-card h2 { margin: 9px 0 8px; font-size: 20px; }
|
||||
.welcome-card p { margin: 0 auto 20px; max-width: 420px; color: #8B6B58; line-height: 1.6; font-size: 14px; }
|
||||
.starter-list { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; }
|
||||
.starter-list button { border: 1px solid #FFD1A8; color: #C15F18; background: #FFF4E8; border-radius: 20px; padding: 8px 12px; cursor: pointer; }
|
||||
.message-row { display: flex; gap: 9px; margin: 18px 0; align-items: flex-end; }
|
||||
.welcome-avatar { width: 64px; height: 64px; display: grid; place-items: center; margin: 0 auto 14px; overflow: hidden; border: 3px solid #fff; border-radius: 50%; background: #FFE4C7; box-shadow: 0 7px 16px rgba(181, 99, 35, .18); font-size: 32px; }.welcome-avatar img { width: 100%; height: 100%; object-fit: cover; }
|
||||
.welcome-card h2 { margin: 0 0 8px; font-size: 20px; }.welcome-description { max-width: 340px; margin: 0 auto; color: #8B6B58; font-size: 14px; line-height: 1.65; }
|
||||
.message-row { display: flex; gap: 10px; margin: 18px 0; align-items: flex-start; }
|
||||
.message-row.user { justify-content: flex-end; }
|
||||
.message-avatar { flex: 0 0 auto; width: 30px; height: 30px; display: grid; place-items: center; border-radius: 10px; background: #FFE4C7; }
|
||||
.message-avatar { flex: 0 0 auto; width: 42px; height: 42px; display: grid; place-items: center; overflow: hidden; border: 2px solid rgba(255,255,255,.9); border-radius: 14px; background: #FFE4C7; box-shadow: 0 3px 10px rgba(96, 52, 21, .12); font-size: 16px; }.message-avatar img { width: 100%; height: 100%; object-fit: cover; }.user-message-face { color: #fff; background: #D97706; }
|
||||
.message-column { max-width: min(78%, 560px); }
|
||||
.message-bubble { padding: 12px 14px; white-space: pre-wrap; line-height: 1.6; font-size: 15px; border-radius: 16px 16px 16px 4px; background: white; box-shadow: 0 3px 12px rgba(96, 52, 21, .07); }
|
||||
.user .message-bubble { color: white; border-radius: 16px 16px 4px 16px; background: #F97316; }
|
||||
.message-bubble { padding: 12px 14px; white-space: pre-wrap; line-height: 1.6; font-size: 15px; border-radius: 4px 16px 16px 16px; background: white; box-shadow: 0 3px 12px rgba(96, 52, 21, .07); }
|
||||
.message-bubble.streaming::after { content: ''; display: inline-block; width: 2px; height: 1.05em; margin-left: 3px; vertical-align: -0.16em; background: currentColor; animation: type-cursor .75s step-end infinite; }
|
||||
.typing-character { display: inline-block; animation: character-in .24s cubic-bezier(.2,.72,.25,1) both; }.typing-character.newline { display: block; height: 0; }
|
||||
.typing-character.markdown-bold { font-weight: 750; color: #2F1A10; }
|
||||
.typing-character.markdown-italic { font-style: italic; }
|
||||
.typing-character.markdown-code { margin: 0 1px; padding: 0 3px; border-radius: 4px; color: #9A3412; background: #FFF0E3; font-family: "SFMono-Regular", Consolas, monospace; font-size: .92em; }
|
||||
.typing-character.markdown-heading { font-weight: 750; font-size: 1.08em; }
|
||||
.user .message-bubble { color: white; border-radius: 16px 4px 16px 16px; background: #F97316; }
|
||||
.message-source { margin: 5px 4px 0; font-size: 11px; color: #A77A5B; }
|
||||
.typing { display: flex; gap: 4px; padding: 14px 16px; }
|
||||
.typing i { width: 5px; height: 5px; border-radius: 50%; background: #F97316; animation: blink 1s infinite alternate; }
|
||||
.typing i:nth-child(2) { animation-delay: .2s; }.typing i:nth-child(3) { animation-delay: .4s; }
|
||||
@keyframes blink { from { opacity: .25; } to { opacity: 1; } }
|
||||
@keyframes type-cursor { 50% { opacity: 0; } }
|
||||
@keyframes character-in { from { opacity: 0; transform: translateY(3px); } to { opacity: 1; transform: translateY(0); } }
|
||||
.chat-error { margin: 4px auto; color: #B42318; font-size: 13px; }.chat-error button { border: 0; background: none; color: #C15F18; cursor: pointer; text-decoration: underline; }
|
||||
.composer { position: fixed; left: 0; right: 0; bottom: 0; display: flex; gap: 10px; padding: 12px max(18px, calc((100vw - 760px) / 2 + 18px)); background: rgba(255,255,255,.92); border-top: 1px solid #F4DCC7; backdrop-filter: blur(12px); }
|
||||
.composer textarea { flex: 1; resize: none; min-height: 22px; max-height: 100px; padding: 11px 13px; border: 1px solid #EED8C5; border-radius: 13px; font: inherit; color: #3B2417; outline: none; }.composer textarea:focus { border-color: #F97316; }
|
||||
|
||||
Reference in New Issue
Block a user