feat(chat): 新增智能助手功能模块
- 添加智能助手路由和导航栏入口 - 实现聊天界面和消息气泡组件 - 添加消息类型定义和本地存储管理 - 实现流式对话API和SSE连接处理 - 新增Markdown消息渲染和消息操作功能 - 添加相关依赖包支持
This commit is contained in:
parent
c234d0b2a8
commit
38958e69fb
|
|
@ -15,12 +15,14 @@
|
|||
"zip": "powershell -Command \"$timestamp = (Get-Date).ToString('yyyyMMdd-HHmmss'); 7z a -tzip dist/shop-web-$timestamp.zip ./dist/* -xr'!*.zip'\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@microsoft/fetch-event-source": "2.0.1",
|
||||
"@vant/touch-emulator": "1.4.0",
|
||||
"axios": "1.7.9",
|
||||
"compressorjs": "1.2.1",
|
||||
"dayjs": "1.11.13",
|
||||
"js-cookie": "3.0.5",
|
||||
"lodash-es": "4.17.21",
|
||||
"marked": "17.0.1",
|
||||
"normalize.css": "8.0.1",
|
||||
"pinia": "3.0.1",
|
||||
"unocss": "66.0.0",
|
||||
|
|
|
|||
|
|
@ -8,6 +8,9 @@ importers:
|
|||
|
||||
.:
|
||||
dependencies:
|
||||
'@microsoft/fetch-event-source':
|
||||
specifier: 2.0.1
|
||||
version: 2.0.1
|
||||
'@vant/touch-emulator':
|
||||
specifier: 1.4.0
|
||||
version: 1.4.0
|
||||
|
|
@ -26,6 +29,9 @@ importers:
|
|||
lodash-es:
|
||||
specifier: 4.17.21
|
||||
version: 4.17.21
|
||||
marked:
|
||||
specifier: 17.0.1
|
||||
version: 17.0.1
|
||||
normalize.css:
|
||||
specifier: 8.0.1
|
||||
version: 8.0.1
|
||||
|
|
@ -1242,6 +1248,9 @@ packages:
|
|||
'@jridgewell/trace-mapping@0.3.25':
|
||||
resolution: {integrity: sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==}
|
||||
|
||||
'@microsoft/fetch-event-source@2.0.1':
|
||||
resolution: {integrity: sha512-W6CLUJ2eBMw3Rec70qrsEW0jOm/3twwJv21mrmj2yORiaVmVYGS4sSS5yUwvQc1ZlDLYGPnClVWmUUMagKNsfA==}
|
||||
|
||||
'@nodelib/fs.scandir@2.1.5':
|
||||
resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}
|
||||
engines: {node: '>= 8'}
|
||||
|
|
@ -2763,6 +2772,11 @@ packages:
|
|||
markdown-table@3.0.4:
|
||||
resolution: {integrity: sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==}
|
||||
|
||||
marked@17.0.1:
|
||||
resolution: {integrity: sha512-boeBdiS0ghpWcSwoNm/jJBwdpFaMnZWRzjA6SkUMYb40SVaN1x7mmfGKp0jvexGcx+7y2La5zRZsYFZI6Qpypg==}
|
||||
engines: {node: '>= 20'}
|
||||
hasBin: true
|
||||
|
||||
math-intrinsics@1.1.0:
|
||||
resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
|
@ -4845,6 +4859,8 @@ snapshots:
|
|||
'@jridgewell/resolve-uri': 3.1.2
|
||||
'@jridgewell/sourcemap-codec': 1.5.0
|
||||
|
||||
'@microsoft/fetch-event-source@2.0.1': {}
|
||||
|
||||
'@nodelib/fs.scandir@2.1.5':
|
||||
dependencies:
|
||||
'@nodelib/fs.stat': 2.0.5
|
||||
|
|
@ -6580,6 +6596,8 @@ snapshots:
|
|||
|
||||
markdown-table@3.0.4: {}
|
||||
|
||||
marked@17.0.1: {}
|
||||
|
||||
math-intrinsics@1.1.0: {}
|
||||
|
||||
mdast-util-find-and-replace@3.0.2:
|
||||
|
|
|
|||
|
|
@ -0,0 +1,121 @@
|
|||
const AGENT_BASE_URL = 'http://115.190.18.84:7328/api/agent';
|
||||
// const AGENT_BASE_URL = 'http://localhost:7328/api/agent';
|
||||
|
||||
import { useWxStore } from '@/pinia/stores/wx';
|
||||
import { fetchEventSource } from '@microsoft/fetch-event-source';
|
||||
|
||||
export const baseInfoApi = () => {
|
||||
return fetch(`${AGENT_BASE_URL}`, {
|
||||
method: 'GET',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 流式对话接口,返回流式 JSON 数据,形如 {"text":"我来"}
|
||||
* @param message 用户消息
|
||||
* @param callbacks 回调函数对象
|
||||
* @param options 可选配置,包含 abort signal
|
||||
* @example
|
||||
* // 使用示例:
|
||||
* streamApi('你好', {
|
||||
* onopen(response) {
|
||||
* console.log('连接已建立', response);
|
||||
* },
|
||||
* onmessage(data) {
|
||||
* // data 是服务器发送的原始字符串,如 '{"text":"我来"}'
|
||||
* console.log('收到消息:', data);
|
||||
* },
|
||||
* onclose() {
|
||||
* console.log('连接已关闭');
|
||||
* },
|
||||
* onerror(error) {
|
||||
* console.error('连接错误:', error);
|
||||
* }
|
||||
* }, { signal: abortController.signal });
|
||||
*/
|
||||
export const streamApi = (
|
||||
message: string,
|
||||
callbacks: {
|
||||
onopen?: (response: Response) => void;
|
||||
onmessage?: (data: string) => void;
|
||||
onclose?: () => void;
|
||||
onerror?: (error: Error) => void;
|
||||
},
|
||||
options?: { signal?: AbortSignal; thread?: string; resource?: string }
|
||||
) => {
|
||||
const wxStore = useWxStore();
|
||||
const thread = options?.thread;
|
||||
const resource = options?.resource;
|
||||
|
||||
const requestBody: Record<string, any> = {
|
||||
message: `企业微信id:${wxStore.corpid}
|
||||
${message}`,
|
||||
options: {
|
||||
temperature: 0.8,
|
||||
/* thinking: {
|
||||
type: 'enabled'
|
||||
} */
|
||||
}
|
||||
};
|
||||
|
||||
if (thread && resource) {
|
||||
requestBody.options.memory = {
|
||||
thread,
|
||||
resource
|
||||
};
|
||||
}
|
||||
|
||||
fetchEventSource(`${AGENT_BASE_URL}/stream`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
signal: options?.signal,
|
||||
async onopen(response) {
|
||||
// 检查响应是否正常
|
||||
if (response.ok && response.headers.get('content-type')?.includes('text/event-stream')) {
|
||||
// 连接成功,调用 onopen 回调
|
||||
callbacks.onopen?.(response);
|
||||
} else {
|
||||
// 如果响应不正常,抛出错误
|
||||
throw new Error(`SSE 连接失败: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
},
|
||||
onmessage(msg) {
|
||||
// 处理服务器发送的消息
|
||||
// msg.data 应该是 JSON 字符串,如 {"text":"..."}
|
||||
try {
|
||||
const data = msg.data;
|
||||
console.log('Received message:', data);
|
||||
if (data && data !== '[DONE]') {
|
||||
callbacks.onmessage?.(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('处理 SSE 消息时出错:', error);
|
||||
}
|
||||
},
|
||||
onclose() {
|
||||
// 连接关闭
|
||||
console.log('SSE 连接已关闭');
|
||||
callbacks.onclose?.();
|
||||
},
|
||||
onerror(err) {
|
||||
// 发生错误
|
||||
console.error('SSE 连接错误:', err);
|
||||
callbacks.onerror?.(err instanceof Error ? err : new Error(String(err)));
|
||||
|
||||
// 重新抛出错误以停止重试
|
||||
throw err;
|
||||
},
|
||||
}).catch(error => {
|
||||
// 捕获 fetchEventSource 的 Promise 拒绝
|
||||
if (error.name !== 'AbortError') {
|
||||
console.error('fetchEventSource 错误:', error);
|
||||
callbacks.onerror?.(error instanceof Error ? error : new Error(String(error)));
|
||||
} else {
|
||||
// AbortError 是正常的取消操作,不需要调用 onerror
|
||||
console.log('请求已被取消');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
/** 消息角色 */
|
||||
export type MessageRole = "user" | "assistant" | "system"
|
||||
|
||||
/** 消息状态 */
|
||||
export type MessageStatus = "pending" | "sending" | "sent" | "error"
|
||||
|
||||
/** 消息对象 */
|
||||
export interface ChatMessage {
|
||||
id: string
|
||||
role: MessageRole
|
||||
content: string
|
||||
timestamp: number
|
||||
status: MessageStatus
|
||||
extra?: Record<string, unknown>
|
||||
}
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
import type { ChatMessage } from "@/common/types/chat"
|
||||
|
||||
const CHAT_HISTORY_KEY = "chat_history";
|
||||
const CHAT_RESOURCE_KEY = "chat_resource";
|
||||
const CHAT_THREAD_KEY = "chat_thread";
|
||||
|
||||
export const chatStorage = {
|
||||
save(messages: ChatMessage[]) {
|
||||
try {
|
||||
localStorage.setItem(CHAT_HISTORY_KEY, JSON.stringify(messages))
|
||||
}
|
||||
catch (e) {
|
||||
console.error("保存对话历史失败", e)
|
||||
}
|
||||
},
|
||||
|
||||
load(): ChatMessage[] {
|
||||
try {
|
||||
const data = localStorage.getItem(CHAT_HISTORY_KEY)
|
||||
return data ? JSON.parse(data) : []
|
||||
}
|
||||
catch (e) {
|
||||
console.error("加载对话历史失败", e)
|
||||
return []
|
||||
}
|
||||
},
|
||||
|
||||
clear() {
|
||||
localStorage.removeItem(CHAT_HISTORY_KEY)
|
||||
localStorage.removeItem(CHAT_THREAD_KEY)
|
||||
},
|
||||
|
||||
getResource(): string {
|
||||
let resource = localStorage.getItem(CHAT_RESOURCE_KEY)
|
||||
if (!resource) {
|
||||
resource = `user-${Math.random().toString(36).substring(2, 11)}`
|
||||
localStorage.setItem(CHAT_RESOURCE_KEY, resource)
|
||||
}
|
||||
return resource
|
||||
},
|
||||
|
||||
getThread(): string {
|
||||
let thread = localStorage.getItem(CHAT_THREAD_KEY)
|
||||
if (!thread) {
|
||||
thread = `t-${Date.now()}`
|
||||
localStorage.setItem(CHAT_THREAD_KEY, thread)
|
||||
}
|
||||
return thread
|
||||
},
|
||||
|
||||
clearThread() {
|
||||
localStorage.removeItem(CHAT_THREAD_KEY)
|
||||
}
|
||||
}
|
||||
|
||||
export const intro = `
|
||||
您好!我是您的智能助手,很高兴为您服务!😊
|
||||
我可以帮您做以下事情:
|
||||
**1. 查询商品信息**
|
||||
- 查看商品列表或单个商品详情
|
||||
- 按价格、分类、状态等条件筛选商品
|
||||
- 支持模糊搜索商品名称
|
||||
**2. 查询门店和智能柜**
|
||||
- 查看您企业下的所有门店列表
|
||||
- 查询门店的运行模式(支付、审批、借还、会员、耗材、暂存等)
|
||||
- 查看智能柜的详细信息
|
||||
**3. 查询借还记录**
|
||||
- 查看商品的借出和归还记录
|
||||
- 按商品、格口、状态等条件筛选动态记录
|
||||
**使用示例:**
|
||||
- \"帮我查一下所有商品\"
|
||||
- \"查看XX门店的智能柜信息\"
|
||||
- \"查询最近借出的商品记录\"
|
||||
- \"价格在100-500元之间的商品有哪些\"
|
||||
有什么我可以帮您的吗?随时告诉我!✨
|
||||
`
|
||||
|
|
@ -21,6 +21,12 @@ const tabbarItemList = computed(() => {
|
|||
icon: 'manager-o',
|
||||
path: '/cabinet'
|
||||
});
|
||||
|
||||
items.push({
|
||||
title: '智能助手',
|
||||
icon: 'chat-o',
|
||||
path: '/chat'
|
||||
});
|
||||
}
|
||||
|
||||
if (names.includes('ShopGoods')) {
|
||||
|
|
|
|||
|
|
@ -316,6 +316,25 @@ export const routes: RouteRecordRaw[] = [
|
|||
meta: {
|
||||
title: "登录"
|
||||
}
|
||||
},
|
||||
{
|
||||
path: "/chat",
|
||||
component: () => import("@/views/chat/index.vue"),
|
||||
name: "Chat",
|
||||
meta: {
|
||||
title: "智能助手",
|
||||
layout: {
|
||||
navBar: {
|
||||
showNavBar: false,
|
||||
showLeftArrow: true
|
||||
},
|
||||
tabbar: {
|
||||
showTabbar: true,
|
||||
icon: "user-o"
|
||||
}
|
||||
},
|
||||
requiresAuth: true
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,183 @@
|
|||
<template>
|
||||
<div :class="['message-bubble', `message-${message.role}`]">
|
||||
<van-image
|
||||
v-if="message.role === 'user'"
|
||||
round
|
||||
width="36px"
|
||||
height="36px"
|
||||
:src="userAvatar"
|
||||
class="avatar"
|
||||
/>
|
||||
<div class="bubble-content" @click="showMenu = true">
|
||||
<div v-if="message.status === 'pending'" class="thinking">
|
||||
<span class="thinking-dot">●</span>
|
||||
<span class="thinking-dot">●</span>
|
||||
<span class="thinking-dot">●</span>
|
||||
</div>
|
||||
<div v-else class="message-text" v-html="marked.parse(message.content)"></div>
|
||||
</div>
|
||||
<van-image
|
||||
v-if="message.role === 'assistant'"
|
||||
round
|
||||
width="36px"
|
||||
height="36px"
|
||||
:src="aiAvatar"
|
||||
class="avatar"
|
||||
/>
|
||||
<div v-if="message.role === 'user' && message.status === 'error'" class="message-status">
|
||||
<span class="error" @click.stop="emit('retry', message)">重试</span>
|
||||
</div>
|
||||
<van-popup
|
||||
v-model:show="showMenu"
|
||||
position="bottom"
|
||||
round
|
||||
:style="{ height: '30%' }"
|
||||
>
|
||||
<div class="action-sheet">
|
||||
<van-button block @click="handleCopy">复制</van-button>
|
||||
<van-button block @click="handleDelete" v-if="message.role === 'user'">删除</van-button>
|
||||
</div>
|
||||
</van-popup>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import { showConfirmDialog, showToast } from "vant";
|
||||
import type { ChatMessage } from "@/common/types/chat";
|
||||
import { marked } from 'marked';
|
||||
|
||||
const props = defineProps<{
|
||||
message: ChatMessage
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: "retry", msg: ChatMessage): void
|
||||
(e: "delete", msg: ChatMessage): void
|
||||
}>()
|
||||
|
||||
const showMenu = ref(false)
|
||||
const userAvatar = ""
|
||||
const aiAvatar = ""
|
||||
|
||||
const handleCopy = () => {
|
||||
navigator.clipboard.writeText(props.message.content)
|
||||
showToast("已复制")
|
||||
showMenu.value = false
|
||||
}
|
||||
|
||||
const handleDelete = () => {
|
||||
showConfirmDialog({
|
||||
message: "确定删除该消息?",
|
||||
confirmButtonColor: "#f44"
|
||||
}).then(() => {
|
||||
emit("delete", props.message)
|
||||
showMenu.value = false
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.message-bubble {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 16px;
|
||||
position: relative;
|
||||
|
||||
&.message-user {
|
||||
flex-direction: row-reverse;
|
||||
|
||||
.bubble-content {
|
||||
background: #1989fa;
|
||||
color: #fff;
|
||||
border-radius: 16px 4px 16px 16px;
|
||||
}
|
||||
}
|
||||
|
||||
&.message-assistant {
|
||||
flex-direction: column-reverse;
|
||||
|
||||
.bubble-content {
|
||||
background: #fff;
|
||||
color: #333;
|
||||
border-radius: 4px 16px 16px 16px;
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.avatar {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.bubble-content {
|
||||
max-width: 70%;
|
||||
padding: 12px 16px;
|
||||
word-break: break-word;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.message-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
white-space: pre-wrap;
|
||||
line-height: 1.2;
|
||||
:deep(p) {
|
||||
margin: 0;
|
||||
}
|
||||
:deep(ul) {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
}
|
||||
|
||||
.thinking {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.thinking-dot {
|
||||
animation: blink 1.4s infinite;
|
||||
color: #999;
|
||||
font-size: 12px;
|
||||
|
||||
&:nth-child(2) {
|
||||
animation-delay: 0.2s;
|
||||
}
|
||||
|
||||
&:nth-child(3) {
|
||||
animation-delay: 0.4s;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes blink {
|
||||
0%, 60%, 100% {
|
||||
opacity: 0.3;
|
||||
}
|
||||
30% {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.message-status {
|
||||
position: absolute;
|
||||
right: 60px;
|
||||
bottom: 0;
|
||||
font-size: 12px;
|
||||
|
||||
.error {
|
||||
color: #f44;
|
||||
}
|
||||
}
|
||||
|
||||
.action-sheet {
|
||||
padding: 16px;
|
||||
|
||||
> * {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,305 @@
|
|||
<template>
|
||||
<div class="chat-page">
|
||||
<div ref="scrollRef" class="chat-messages" @scroll="onScroll">
|
||||
<div v-if="loadingHistory" class="loading-history">
|
||||
<van-loading size="16px">加载中...</van-loading>
|
||||
</div>
|
||||
<template v-for="msg in messages" :key="msg.id">
|
||||
<div v-if="shouldShowTime(msg.timestamp)" class="message-time">
|
||||
{{ formatTime(msg.timestamp) }}
|
||||
</div>
|
||||
<ChatBubble
|
||||
:message="msg"
|
||||
@retry="onRetry"
|
||||
@delete="onDelete(msg)"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
<div class="clear-float" @click="onMoreAction">
|
||||
<van-icon name="delete-o" />
|
||||
</div>
|
||||
<div class="chat-input-area">
|
||||
<div class="input-row">
|
||||
<van-field
|
||||
v-model="inputValue"
|
||||
type="textarea"
|
||||
autosize
|
||||
placeholder="请输入消息..."
|
||||
maxlength="500"
|
||||
show-word-limit
|
||||
class="message-input"
|
||||
@keydown.enter.exact.prevent="onSend"
|
||||
/>
|
||||
<van-button
|
||||
type="primary"
|
||||
size="small"
|
||||
:loading="sending"
|
||||
:disabled="!inputValue.trim() || isThinking"
|
||||
@click="onSend"
|
||||
>
|
||||
发送
|
||||
</van-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, nextTick, watch, onMounted, onUnmounted } from "vue"
|
||||
import { useRouter } from "vue-router"
|
||||
import { showToast, showFailToast, showConfirmDialog } from "vant"
|
||||
import ChatBubble from "./components/ChatBubble.vue"
|
||||
import type { ChatMessage } from "@/common/types/chat"
|
||||
import { chatStorage, intro } from "@/common/utils/storage"
|
||||
import { streamApi } from "@/common/apis/agent"
|
||||
|
||||
const router = useRouter()
|
||||
const abortController = ref<AbortController>()
|
||||
|
||||
const agentName = ref("智能助手")
|
||||
const inputValue = ref("")
|
||||
const messages = ref<ChatMessage[]>([])
|
||||
const isThinking = ref(false)
|
||||
const sending = ref(false)
|
||||
const loadingHistory = ref(false)
|
||||
const scrollRef = ref<HTMLElement>()
|
||||
const currentAiMsgId = ref<string>("")
|
||||
|
||||
onMounted(() => {
|
||||
messages.value = chatStorage.load()
|
||||
|
||||
// 新对话时直接输出intro
|
||||
if (messages.value.length === 0) {
|
||||
const aiMsg: ChatMessage = {
|
||||
id: (Date.now() + 1).toString(),
|
||||
role: "assistant",
|
||||
content: intro,
|
||||
timestamp: Date.now(),
|
||||
status: "sent"
|
||||
}
|
||||
messages.value.push(aiMsg)
|
||||
}
|
||||
|
||||
nextTick(() => {
|
||||
scrollToBottom()
|
||||
})
|
||||
})
|
||||
|
||||
watch(messages, () => {
|
||||
chatStorage.save(messages.value)
|
||||
}, { deep: true })
|
||||
|
||||
const loadHistory = async () => {
|
||||
if (loadingHistory.value) return
|
||||
loadingHistory.value = true
|
||||
try {
|
||||
await new Promise(resolve => setTimeout(resolve, 500))
|
||||
}
|
||||
finally {
|
||||
loadingHistory.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const onSend = async () => {
|
||||
const content = inputValue.value.trim()
|
||||
if (!content || isThinking.value) return
|
||||
|
||||
const userMsg: ChatMessage = {
|
||||
id: Date.now().toString(),
|
||||
role: "user",
|
||||
content,
|
||||
timestamp: Date.now(),
|
||||
status: "sent"
|
||||
}
|
||||
|
||||
messages.value.push(userMsg)
|
||||
inputValue.value = ""
|
||||
sending.value = true
|
||||
await scrollToBottom()
|
||||
|
||||
isThinking.value = true
|
||||
sending.value = false
|
||||
|
||||
// 创建AI消息占位
|
||||
const aiMsgId = (Date.now() + 1).toString()
|
||||
currentAiMsgId.value = aiMsgId
|
||||
const aiMsg: ChatMessage = {
|
||||
id: aiMsgId,
|
||||
role: "assistant",
|
||||
content: "",
|
||||
timestamp: Date.now(),
|
||||
status: "pending"
|
||||
}
|
||||
messages.value.push(aiMsg)
|
||||
|
||||
// 创建 AbortController
|
||||
abortController.value = new AbortController()
|
||||
|
||||
const thread = chatStorage.getThread()
|
||||
const resource = chatStorage.getResource()
|
||||
|
||||
streamApi(
|
||||
content,
|
||||
{
|
||||
onmessage(data) {
|
||||
try {
|
||||
const parsed = JSON.parse(data)
|
||||
if (parsed.text) {
|
||||
const msg = messages.value.find(m => m.id === aiMsgId)
|
||||
if (msg) {
|
||||
msg.status = "sent"
|
||||
msg.content += parsed.text
|
||||
scrollToBottom()
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
console.warn("解析SSE消息失败:", e)
|
||||
}
|
||||
},
|
||||
onclose() {
|
||||
const msg = messages.value.find(m => m.id === aiMsgId)
|
||||
if (msg) {
|
||||
msg.status = "sent"
|
||||
}
|
||||
isThinking.value = false
|
||||
abortController.value = undefined
|
||||
},
|
||||
onerror(error) {
|
||||
const msg = messages.value.find(m => m.id === aiMsgId)
|
||||
if (msg) {
|
||||
msg.status = "error"
|
||||
}
|
||||
showFailToast("连接失败,请重试")
|
||||
isThinking.value = false
|
||||
abortController.value = undefined
|
||||
}
|
||||
},
|
||||
{ signal: abortController.value.signal, thread, resource }
|
||||
)
|
||||
}
|
||||
|
||||
const scrollToBottom = async () => {
|
||||
await nextTick()
|
||||
if (scrollRef.value) {
|
||||
scrollRef.value.scrollTop = scrollRef.value.scrollHeight
|
||||
}
|
||||
}
|
||||
|
||||
const onScroll = (e: Event) => {
|
||||
const target = e.target as HTMLElement
|
||||
if (target.scrollTop < 50 && !loadingHistory.value) {
|
||||
loadHistory()
|
||||
}
|
||||
}
|
||||
|
||||
const shouldShowTime = (timestamp: number) => {
|
||||
if (messages.value.length === 0) return true
|
||||
const lastMsg = messages.value[messages.value.length - 1]
|
||||
return timestamp - lastMsg.timestamp > 300000
|
||||
}
|
||||
|
||||
const formatTime = (timestamp: number) => {
|
||||
const date = new Date(timestamp)
|
||||
return `${date.getHours().toString().padStart(2, "0")}:${date.getMinutes().toString().padStart(2, "0")}`
|
||||
}
|
||||
|
||||
const onMoreAction = () => {
|
||||
showConfirmDialog({
|
||||
message: "确定清空对话历史?",
|
||||
confirmButtonColor: "#f44"
|
||||
}).then(() => {
|
||||
messages.value = []
|
||||
chatStorage.clear()
|
||||
chatStorage.clearThread()
|
||||
})
|
||||
}
|
||||
|
||||
const onBack = () => {
|
||||
router.back()
|
||||
}
|
||||
|
||||
const onRetry = () => {
|
||||
const lastUserMsg = messages.value.filter(m => m.role === "user").pop()
|
||||
if (lastUserMsg) {
|
||||
inputValue.value = lastUserMsg.content
|
||||
onSend()
|
||||
}
|
||||
}
|
||||
|
||||
// 页面销毁时取消请求
|
||||
onUnmounted(() => {
|
||||
abortController.value?.abort()
|
||||
})
|
||||
|
||||
const onDelete = (msg: ChatMessage) => {
|
||||
const index = messages.value.findIndex(m => m.id === msg.id)
|
||||
if (index > -1) {
|
||||
messages.value.splice(index, 1)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.chat-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: calc(100vh - 50px);
|
||||
background: #f7f8fa;
|
||||
}
|
||||
|
||||
.chat-messages {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.message-time {
|
||||
text-align: center;
|
||||
color: #999;
|
||||
font-size: 12px;
|
||||
margin: 16px 0;
|
||||
}
|
||||
|
||||
.loading-history {
|
||||
text-align: center;
|
||||
padding: 16px;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.chat-input-area {
|
||||
background: #fff;
|
||||
border-top: 1px solid #eee;
|
||||
}
|
||||
|
||||
.input-row {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
padding: 12px;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.message-input {
|
||||
flex: 1;
|
||||
background: #f7f8fa;
|
||||
border-radius: 20px;
|
||||
padding: 8px 12px;
|
||||
}
|
||||
|
||||
.clear-float {
|
||||
position: fixed;
|
||||
right: 20px;
|
||||
bottom: 290px;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
background: #fff;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
|
||||
color: #666;
|
||||
font-size: 20px;
|
||||
z-index: 100;
|
||||
}
|
||||
</style>
|
||||
Loading…
Reference in New Issue