initial commit
This commit is contained in:
+16
@@ -0,0 +1,16 @@
|
||||
<template>
|
||||
<el-config-provider :locale="zhCn">
|
||||
<router-view />
|
||||
</el-config-provider>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
// Element Plus 的默认语言包是**英文**:ElMessageBox 的「确定 / 取消」、
|
||||
// el-popconfirm 的按钮等内置文案都会显示成 OK / Cancel,在中文应用里很突兀。
|
||||
// 这里统一注入中文语言包。
|
||||
//
|
||||
// 注:ElConfigProvider 的 render 是 renderSlot,**不产生额外 DOM 元素**,
|
||||
// 所以保持单根结构不会破坏 `.chat-layout` 的 100vh 高度链。
|
||||
// 若未来把它换成会产生包裹层的写法,需重新检查各页面的高度布局。
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
</script>
|
||||
@@ -0,0 +1,498 @@
|
||||
<template>
|
||||
<div class="chat-panel">
|
||||
<div class="chat-panel__messages-wrapper">
|
||||
<div ref="messageContainerRef" class="chat-panel__messages" @scroll="handleMessageScroll">
|
||||
<transition-group name="message-list" tag="div" class="chat-panel__message-list">
|
||||
<MessageItem
|
||||
v-for="message in messages"
|
||||
:key="message.id"
|
||||
:message="message"
|
||||
@delete="emit('delete-message', $event)"
|
||||
@resend="emit('resend-message', $event)"
|
||||
@regenerate="emit('regenerate-message', $event)"
|
||||
/>
|
||||
</transition-group>
|
||||
|
||||
<!-- 空状态(参考腾讯元宝):大标题 + 圆角胶囊推荐问题,分行居中、偏上摆放。
|
||||
点击只把问题填进输入框,不自动发送,用户可以改完再发。 -->
|
||||
<div v-if="!messages.length" class="chat-panel__empty">
|
||||
<div class="chat-panel__empty-head">
|
||||
<span class="chat-panel__empty-avatar">
|
||||
<el-icon><Cpu /></el-icon>
|
||||
</span>
|
||||
<h2 class="chat-panel__empty-title">有什么我能帮你的吗?</h2>
|
||||
</div>
|
||||
<div class="chat-panel__empty-suggestions">
|
||||
<button
|
||||
v-for="question in SUGGESTION_QUESTIONS"
|
||||
:key="question"
|
||||
type="button"
|
||||
class="chat-panel__suggestion"
|
||||
@click="handleSuggestionClick(question)"
|
||||
>
|
||||
{{ question }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<transition name="fade-slide">
|
||||
<el-button
|
||||
v-if="showBackToBottom"
|
||||
class="chat-panel__back-bottom"
|
||||
type="primary"
|
||||
circle
|
||||
@click="handleBackToBottom"
|
||||
>
|
||||
<el-icon><Bottom /></el-icon>
|
||||
</el-button>
|
||||
</transition>
|
||||
</div>
|
||||
|
||||
<div class="chat-panel__footer">
|
||||
<div class="chat-panel__footer-toolbar">
|
||||
<div class="chat-panel__actions">
|
||||
<!-- 会话主体存在 localStorage(跟浏览器配置档走:清缓存 / 换机器 /
|
||||
无痕窗口关闭都会丢),所以保留这两个命令作为唯一的备份/恢复手段。
|
||||
配置的导入导出已废弃:配置已硬编码在 constants/index.ts,
|
||||
再导出会往磁盘落一个含明文 token 的 json,风险大于收益。 -->
|
||||
<el-dropdown @command="handleDataCommand">
|
||||
<el-button>
|
||||
会话备份
|
||||
<el-icon class="el-icon--right"><ArrowDown /></el-icon>
|
||||
</el-button>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item command="export-sessions">导出会话</el-dropdown-item>
|
||||
<el-dropdown-item command="import-sessions">导入会话</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
<el-button :disabled="chatStore.isRequesting" @click="emit('clear-session')">清空当前会话</el-button>
|
||||
<el-button v-if="chatStore.isRequesting" type="danger" @click="emit('stop')">停止生成</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<input ref="fileInputRef" type="file" accept="application/json" class="chat-panel__file-input" @change="handleImportFileChange" />
|
||||
|
||||
<div class="chat-panel__composer">
|
||||
<el-input
|
||||
ref="composerRef"
|
||||
v-model="inputValue"
|
||||
type="textarea"
|
||||
:rows="4"
|
||||
resize="none"
|
||||
placeholder="请输入内容,Enter 发送,Shift+Enter 换行,Ctrl+Enter 快捷发送"
|
||||
@keydown="handleKeydown"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="chat-panel__submit">
|
||||
<div class="chat-panel__submit-left">
|
||||
<div class="chat-panel__hint">{{ inputHintText }}</div>
|
||||
</div>
|
||||
<el-button type="primary" :loading="chatStore.isRequesting" @click="handleSend">发送消息</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import { ArrowDown, Bottom, Cpu } from '@element-plus/icons-vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import type {
|
||||
ChatMessage,
|
||||
ExportedChatSessionsPayload,
|
||||
MessageActionPayload,
|
||||
SendMessagePayload,
|
||||
} from '../types'
|
||||
import { useChatStore } from '../stores/chat'
|
||||
import { useConfigStore } from '../stores/config'
|
||||
import MessageItem from './MessageItem.vue'
|
||||
|
||||
const AUTO_SCROLL_THRESHOLD = 80
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
messages: ChatMessage[]
|
||||
}>(),
|
||||
{
|
||||
messages: () => [],
|
||||
},
|
||||
)
|
||||
|
||||
const emit = defineEmits<{
|
||||
send: [payload: SendMessagePayload]
|
||||
stop: []
|
||||
'clear-session': []
|
||||
'delete-message': [payload: MessageActionPayload]
|
||||
'resend-message': [payload: MessageActionPayload]
|
||||
'regenerate-message': [payload: MessageActionPayload]
|
||||
}>()
|
||||
|
||||
const chatStore = useChatStore()
|
||||
const configStore = useConfigStore()
|
||||
const inputValue = ref('')
|
||||
const messageContainerRef = ref<HTMLDivElement | null>(null)
|
||||
const shouldAutoScroll = ref(true)
|
||||
const fileInputRef = ref<HTMLInputElement | null>(null)
|
||||
|
||||
/** el-input 实例上我们只用得到这两个成员(结构化声明,避免额外类型依赖) */
|
||||
interface ComposerInstance {
|
||||
focus: () => void
|
||||
textarea?: HTMLTextAreaElement | null
|
||||
}
|
||||
const composerRef = ref<ComposerInstance | null>(null)
|
||||
|
||||
/**
|
||||
* 空状态推荐问题 —— 贴合本项目领域(百家乐 AI 策略对话:
|
||||
* 结合当前注码 / 打法表格上下文产出策略代码)。
|
||||
* 点击只填入输入框、不发送,文案可整条替换。
|
||||
*/
|
||||
const SUGGESTION_QUESTIONS: string[] = [
|
||||
'分析打法表的庄闲比,这路子值不值得继续跟?',
|
||||
'检查注码表的止损点,会不会出现一把打穿的情况?',
|
||||
'结合最近 20 局的结果,给我下一手的注码建议',
|
||||
'从打法表生成一份策略代码,要求带连输降注和止盈止损',
|
||||
'解释策略代码里注码倍数与最大连输参数的含义',
|
||||
]
|
||||
|
||||
function handleSuggestionClick(question: string): void {
|
||||
inputValue.value = question
|
||||
nextTick(() => {
|
||||
composerRef.value?.focus()
|
||||
const textarea = composerRef.value?.textarea
|
||||
if (textarea && typeof textarea.setSelectionRange === 'function') {
|
||||
textarea.setSelectionRange(question.length, question.length)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const hasStoppedMessage = computed(() => props.messages.some((message) => message.status === 'stopped'))
|
||||
const showBackToBottom = computed(() => props.messages.length > 0 && !shouldAutoScroll.value)
|
||||
|
||||
const inputHintText = computed(() => {
|
||||
if (chatStore.isRequesting) {
|
||||
return '正在接收模型回复,请勿重复提交。'
|
||||
}
|
||||
|
||||
if (hasStoppedMessage.value) {
|
||||
return '上一次生成已手动停止,可继续补充提问。'
|
||||
}
|
||||
|
||||
return '请输入你的提问,然后点击"发送消息"。'
|
||||
})
|
||||
|
||||
watch(
|
||||
() => props.messages,
|
||||
async () => {
|
||||
await nextTick()
|
||||
if (shouldAutoScroll.value) {
|
||||
scrollToBottom()
|
||||
}
|
||||
},
|
||||
{ deep: true, immediate: true },
|
||||
)
|
||||
|
||||
function resetComposer(): void {
|
||||
inputValue.value = ''
|
||||
}
|
||||
|
||||
function handleSend(): void {
|
||||
const content = inputValue.value.trim()
|
||||
if (!content) {
|
||||
ElMessage.warning('请输入消息内容后再发送')
|
||||
return
|
||||
}
|
||||
|
||||
emit('send', { content })
|
||||
resetComposer()
|
||||
shouldAutoScroll.value = true
|
||||
}
|
||||
|
||||
function handleKeydown(event: KeyboardEvent): void {
|
||||
if (event.key !== 'Enter') return
|
||||
|
||||
if (event.shiftKey) {
|
||||
return
|
||||
}
|
||||
|
||||
if (event.ctrlKey || !event.shiftKey) {
|
||||
event.preventDefault()
|
||||
handleSend()
|
||||
}
|
||||
}
|
||||
|
||||
function handleMessageScroll(): void {
|
||||
const container = messageContainerRef.value
|
||||
if (!container) return
|
||||
|
||||
const distanceToBottom = container.scrollHeight - container.scrollTop - container.clientHeight
|
||||
shouldAutoScroll.value = distanceToBottom <= AUTO_SCROLL_THRESHOLD
|
||||
}
|
||||
|
||||
function handleBackToBottom(): void {
|
||||
shouldAutoScroll.value = true
|
||||
scrollToBottom()
|
||||
}
|
||||
|
||||
function scrollToBottom(): void {
|
||||
const container = messageContainerRef.value
|
||||
if (!container) return
|
||||
container.scrollTop = container.scrollHeight
|
||||
}
|
||||
|
||||
function downloadJson(filename: string, payload: unknown): void {
|
||||
const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json;charset=utf-8' })
|
||||
const objectUrl = URL.createObjectURL(blob)
|
||||
const link = document.createElement('a')
|
||||
link.href = objectUrl
|
||||
link.download = filename
|
||||
link.click()
|
||||
URL.revokeObjectURL(objectUrl)
|
||||
}
|
||||
|
||||
function handleDataCommand(command: string): void {
|
||||
if (command === 'export-sessions') {
|
||||
const payload = chatStore.exportSessions()
|
||||
downloadJson(`chat-sessions-${payload.exportedAt}.json`, payload)
|
||||
ElMessage.success('会话已导出')
|
||||
return
|
||||
}
|
||||
|
||||
if (command === 'import-sessions') {
|
||||
fileInputRef.value?.click()
|
||||
}
|
||||
}
|
||||
|
||||
async function handleImportFileChange(event: Event): Promise<void> {
|
||||
const target = event.target as HTMLInputElement
|
||||
const file = target.files?.[0]
|
||||
|
||||
if (!file) {
|
||||
target.value = ''
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const text = await file.text()
|
||||
const payload = JSON.parse(text) as ExportedChatSessionsPayload
|
||||
|
||||
if (!chatStore.importSessions(payload)) {
|
||||
ElMessage.error('会话导入失败,文件内容无效')
|
||||
} else {
|
||||
ElMessage.success('会话已导入')
|
||||
}
|
||||
} catch (_error) {
|
||||
ElMessage.error('文件解析失败,请确认导入的是有效 JSON 文件')
|
||||
} finally {
|
||||
target.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.chat-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
// 响应式硬约束:视口 < 568px 时侧栏整体隐藏(见 ChatView + stores/config 的判定阶梯),
|
||||
// 此时聊天面板独占视口;视口连 480 都不到则由根元素 min-width(480px) 兜底,窗口不再缩小。
|
||||
min-width: 480px;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
|
||||
&__messages-wrapper {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
padding: 20px 20px 0;
|
||||
}
|
||||
|
||||
&__messages {
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
padding: 28px 28px 20px;
|
||||
// 屏蔽浅色渐变底色 + 描边(#f7f9fd / #f2f6fb / #e8ecf3):
|
||||
// 深色下会盖住主题底色。参考元宝 —— 内容区不描边,靠层次区分。
|
||||
background: transparent;
|
||||
border: none;
|
||||
border-radius: 20px;
|
||||
}
|
||||
|
||||
&__message-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
&__back-bottom {
|
||||
position: absolute;
|
||||
right: 38px;
|
||||
bottom: 22px;
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
border: none;
|
||||
box-shadow: 0 10px 24px rgba(64, 158, 255, 0.28);
|
||||
}
|
||||
|
||||
&__footer {
|
||||
flex-shrink: 0;
|
||||
// 输入区大圆角卡片(参考元宝):宽度随页面缩放、上限 900px、水平居中;
|
||||
// 容器窄于 930px 时 width = 100% - 30px,两侧 auto margin 恰好各留 15px。
|
||||
width: calc(100% - 30px);
|
||||
max-width: 900px;
|
||||
margin: 14px auto 16px;
|
||||
padding: 14px 16px 16px;
|
||||
background: var(--el-bg-color-overlay);
|
||||
border: 1px solid var(--el-border-color-lighter);
|
||||
border-radius: 20px;
|
||||
box-shadow: 0 12px 32px rgba(15, 23, 42, 0.08);
|
||||
}
|
||||
|
||||
&__footer-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 12px;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
&__actions {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
&__file-input {
|
||||
display: none;
|
||||
}
|
||||
|
||||
&__submit {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
&__submit-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
&__composer {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
&__hint {
|
||||
// 屏蔽硬编码 #8a94a6
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
}
|
||||
|
||||
/* 空状态:偏上摆放(约容器 1/6 处,参考元宝),不做死板的垂直居中 */
|
||||
.chat-panel__empty {
|
||||
min-height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding-top: 12vh;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.chat-panel__empty-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.chat-panel__empty-avatar {
|
||||
width: 46px;
|
||||
height: 46px;
|
||||
border-radius: 50%;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
font-size: 22px;
|
||||
color: #ffffff;
|
||||
background: linear-gradient(135deg, var(--el-color-primary) 0%, #7c9cff 100%);
|
||||
box-shadow: 0 10px 24px rgba(64, 158, 255, 0.35);
|
||||
}
|
||||
|
||||
.chat-panel__empty-title {
|
||||
margin: 0;
|
||||
font-size: 30px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.5px;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
|
||||
.chat-panel__empty-suggestions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
max-width: 860px;
|
||||
margin-top: 30px;
|
||||
padding: 0 16px;
|
||||
}
|
||||
|
||||
.chat-panel__suggestion {
|
||||
padding: 10px 18px;
|
||||
border: 1px solid var(--el-border-color-lighter);
|
||||
border-radius: 999px;
|
||||
background: var(--el-fill-color-light);
|
||||
color: var(--el-text-color-regular);
|
||||
font-size: 14px;
|
||||
line-height: 1.4;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.18s ease, color 0.18s ease, background-color 0.18s ease, transform 0.18s ease;
|
||||
}
|
||||
|
||||
.chat-panel__suggestion:hover {
|
||||
border-color: var(--el-color-primary);
|
||||
background: var(--el-color-primary-light-9);
|
||||
color: var(--el-color-primary);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.chat-panel__suggestion:focus-visible {
|
||||
outline: 2px solid var(--el-color-primary);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.message-list-enter-active,
|
||||
.message-list-leave-active {
|
||||
transition: all 0.25s ease;
|
||||
}
|
||||
|
||||
.message-list-enter-from {
|
||||
opacity: 0;
|
||||
transform: translateY(16px);
|
||||
}
|
||||
|
||||
.message-list-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(-8px);
|
||||
}
|
||||
|
||||
.message-list-move {
|
||||
transition: transform 0.25s ease;
|
||||
}
|
||||
|
||||
.fade-slide-enter-active,
|
||||
.fade-slide-leave-active {
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.fade-slide-enter-from,
|
||||
.fade-slide-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(8px);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,585 @@
|
||||
<template>
|
||||
<div :class="['message-item', `message-item--${message.role}`, { 'message-item--error': message.error }]">
|
||||
<div class="message-item__row">
|
||||
<div :class="['message-item__avatar', `message-item__avatar--${message.role}`]">
|
||||
<el-icon>
|
||||
<UserFilled v-if="message.role === 'user'" />
|
||||
<Cpu v-else />
|
||||
</el-icon>
|
||||
</div>
|
||||
|
||||
<div class="message-item__content">
|
||||
<div class="message-item__header">
|
||||
<div class="message-item__meta">
|
||||
<span class="message-item__name">{{ message.role === 'user' ? '用户' : 'AI 助手' }}</span>
|
||||
<span class="message-item__time">{{ formatTime(message.createdAt) }}</span>
|
||||
</div>
|
||||
<div class="message-item__meta-right">
|
||||
<el-tag v-if="message.status === 'stopped'" size="small" type="warning">已停止</el-tag>
|
||||
<el-tag v-else-if="message.status === 'error'" size="small" type="danger">失败</el-tag>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="message-item__bubble-wrap">
|
||||
<div class="message-item__bubble">
|
||||
<div
|
||||
v-if="message.role === 'assistant'"
|
||||
ref="markdownContainerRef"
|
||||
class="message-item__markdown"
|
||||
v-html="renderedContent"
|
||||
></div>
|
||||
<div v-else-if="message.content" class="message-item__plain">{{ message.content }}</div>
|
||||
<span
|
||||
v-if="message.role === 'assistant' && message.isLoading"
|
||||
class="message-item__stream-cursor"
|
||||
></span>
|
||||
|
||||
<div v-if="message.isLoading" class="message-item__typing">
|
||||
<span class="message-item__typing-label">AI 正在生成</span>
|
||||
<span class="message-item__typing-dots">
|
||||
<i></i>
|
||||
<i></i>
|
||||
<i></i>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="message-item__actions">
|
||||
<el-tooltip content="复制" placement="top">
|
||||
<el-button text circle size="small" @click="handleCopy">
|
||||
<el-icon><DocumentCopy /></el-icon>
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
<el-tooltip v-if="message.role === 'user'" content="重发" placement="top">
|
||||
<el-button text circle size="small" @click="emit('resend', { messageId: message.id })">
|
||||
<el-icon><RefreshRight /></el-icon>
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
<el-tooltip v-if="message.role === 'assistant'" content="重新生成" placement="top">
|
||||
<el-button text circle size="small" @click="emit('regenerate', { messageId: message.id })">
|
||||
<el-icon><Refresh /></el-icon>
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
<el-tooltip content="删除" placement="top">
|
||||
<el-button text circle size="small" @click="emit('delete', { messageId: message.id })">
|
||||
<el-icon><Delete /></el-icon>
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import { Cpu, Delete, DocumentCopy, Refresh, RefreshRight, UserFilled } from '@element-plus/icons-vue'
|
||||
import copy from 'clipboard-copy'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import type { ChatMessage, MessageActionPayload } from '../types'
|
||||
import { renderMarkdown } from '../utils/markdown'
|
||||
import { formatTime } from '../utils/common'
|
||||
|
||||
const props = defineProps<{
|
||||
message: ChatMessage
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
delete: [payload: MessageActionPayload]
|
||||
resend: [payload: MessageActionPayload]
|
||||
regenerate: [payload: MessageActionPayload]
|
||||
}>()
|
||||
|
||||
const markdownContainerRef = ref<HTMLDivElement | null>(null)
|
||||
const renderedContent = computed(() => renderMarkdown(props.message.content || ''))
|
||||
|
||||
watch(
|
||||
renderedContent,
|
||||
async () => {
|
||||
await nextTick()
|
||||
bindCodeCopyActions()
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
async function handleCopy(): Promise<void> {
|
||||
await copy(props.message.content || '')
|
||||
ElMessage.success('消息内容已复制')
|
||||
}
|
||||
|
||||
function getCodeText(codeElement?: Element | null): string {
|
||||
return (codeElement?.textContent || '').replace(/\n+$/g, '')
|
||||
}
|
||||
|
||||
function bindCodeCopyActions(): void {
|
||||
const container = markdownContainerRef.value
|
||||
if (!container) return
|
||||
|
||||
const copyButtons = container.querySelectorAll<HTMLButtonElement>('.md-code-block__copy')
|
||||
copyButtons.forEach((button) => {
|
||||
if (button.dataset.bound === 'true') return
|
||||
|
||||
button.dataset.bound = 'true'
|
||||
button.addEventListener('click', async () => {
|
||||
const codeElement = button.closest('.md-code-block')?.querySelector('pre code')
|
||||
const codeText = getCodeText(codeElement)
|
||||
await copy(codeText)
|
||||
ElMessage.success('代码已复制')
|
||||
})
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.message-item {
|
||||
margin-bottom: 24px;
|
||||
|
||||
&__row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
max-width: min(82%, 920px);
|
||||
}
|
||||
|
||||
&--user &__row {
|
||||
margin-left: auto;
|
||||
flex-direction: row-reverse;
|
||||
}
|
||||
|
||||
&__avatar {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 14px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
font-size: 18px;
|
||||
box-shadow: 0 10px 24px rgba(15, 23, 42, 0.08);
|
||||
|
||||
&--user {
|
||||
color: #ffffff;
|
||||
background: linear-gradient(135deg, #409eff 0%, #7c9cff 100%);
|
||||
}
|
||||
|
||||
&--assistant {
|
||||
// 屏蔽白底浅蓝(#ffffff→#eef4ff / #dbeafe / #2563eb):深色下会是一块刺眼的白圆
|
||||
color: var(--el-color-primary);
|
||||
background: linear-gradient(135deg, var(--el-fill-color-blank) 0%, var(--el-fill-color-light) 100%);
|
||||
border: 1px solid var(--el-border-color-lighter);
|
||||
}
|
||||
}
|
||||
|
||||
&__content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
&__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
&--user &__header {
|
||||
flex-direction: row-reverse;
|
||||
}
|
||||
|
||||
&__meta {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
&__name {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
|
||||
&__time {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
|
||||
&__meta-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-height: 24px;
|
||||
}
|
||||
|
||||
&__bubble-wrap {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
&--user &__bubble-wrap {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
&__bubble {
|
||||
max-width: min(100%, 820px);
|
||||
padding: 16px 18px;
|
||||
border-radius: 18px;
|
||||
line-height: 1.75;
|
||||
box-shadow: 0 10px 28px rgba(15, 23, 42, 0.05);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
&--user &__bubble {
|
||||
background: linear-gradient(135deg, #409eff 0%, #5aa9ff 100%);
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
&--assistant &__bubble {
|
||||
// 屏蔽 rgba(255,255,255,.96) / #1f2937 / #e5e7eb:
|
||||
// 深色下白底卡片过亮,文字对比也不对。用 EP 的 overlay 层做「浮起一层」的层次。
|
||||
background: var(--el-bg-color-overlay);
|
||||
color: var(--el-text-color-primary);
|
||||
border: 1px solid var(--el-border-color-lighter);
|
||||
}
|
||||
|
||||
// 报错气泡必须写在 assistant 规则**之后**:两者同为 (0,2,0),靠源顺序生效。
|
||||
// 原来它在文件最前面,background/border 被 assistant 整条盖掉 —— 报错气泡从来没变过红。
|
||||
// EP danger 变量在深色下自带配套暗底(danger-light-9)。
|
||||
&--error &__bubble {
|
||||
border-color: var(--el-color-danger);
|
||||
background: var(--el-color-danger-light-9);
|
||||
}
|
||||
|
||||
&__plain {
|
||||
font-size: 14px;
|
||||
line-height: 1.65;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
&__markdown {
|
||||
// 屏蔽硬编码 #24292f:随气泡继承(浅色 #303133 / 深色 #e5eaf3)
|
||||
font-size: 14px;
|
||||
line-height: 1.72;
|
||||
word-break: break-word;
|
||||
|
||||
:deep(h1),
|
||||
:deep(h2),
|
||||
:deep(h3),
|
||||
:deep(h4) {
|
||||
margin: 14px 0 8px;
|
||||
line-height: 1.35;
|
||||
color: var(--el-text-color-primary);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
:deep(h1:first-child),
|
||||
:deep(h2:first-child),
|
||||
:deep(h3:first-child),
|
||||
:deep(h4:first-child) {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
:deep(h1) {
|
||||
font-size: 20px;
|
||||
padding-bottom: 8px;
|
||||
border-bottom: 1px solid var(--el-border-color-lighter);
|
||||
}
|
||||
|
||||
:deep(h2) {
|
||||
font-size: 18px;
|
||||
padding-bottom: 6px;
|
||||
border-bottom: 1px solid var(--el-border-color-extra-light);
|
||||
}
|
||||
|
||||
:deep(h3) {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
:deep(h4) {
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
:deep(a) {
|
||||
color: var(--el-color-primary);
|
||||
text-decoration: none;
|
||||
border-bottom: 1px solid var(--el-color-primary-light-5);
|
||||
}
|
||||
|
||||
:deep(a:hover) {
|
||||
color: var(--el-color-primary-dark-2);
|
||||
border-bottom-color: var(--el-color-primary);
|
||||
}
|
||||
|
||||
:deep(hr) {
|
||||
height: 1px;
|
||||
margin: 14px 0;
|
||||
border: none;
|
||||
background: var(--el-border-color-lighter);
|
||||
}
|
||||
|
||||
:deep(.md-code-block) {
|
||||
margin: 10px 0 12px;
|
||||
border: 1px solid var(--el-border-color);
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
// 屏蔽 #f6f8fa 浅底:深色下改用 EP 填充色,代码块在深色里是「略亮一档」的面板
|
||||
background: var(--el-fill-color-light);
|
||||
}
|
||||
|
||||
:deep(.md-code-block:first-child) {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
:deep(.md-code-block:last-child) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
:deep(.md-code-block__toolbar) {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
min-height: 30px;
|
||||
padding: 0 10px;
|
||||
background: var(--el-fill-color);
|
||||
border-bottom: 1px solid var(--el-border-color-lighter);
|
||||
}
|
||||
|
||||
:deep(.md-code-block__language) {
|
||||
font-size: 11px;
|
||||
line-height: 1;
|
||||
color: var(--el-text-color-secondary);
|
||||
text-transform: uppercase;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.03em;
|
||||
}
|
||||
|
||||
:deep(.md-code-block__copy) {
|
||||
border: 1px solid var(--el-border-color);
|
||||
border-radius: 999px;
|
||||
background: var(--el-bg-color-overlay);
|
||||
color: var(--el-text-color-secondary);
|
||||
cursor: pointer;
|
||||
font-size: 11px;
|
||||
line-height: 1;
|
||||
padding: 4px 8px;
|
||||
opacity: 0.75;
|
||||
transition: opacity 0.18s ease, color 0.18s ease, border-color 0.18s ease;
|
||||
}
|
||||
|
||||
:deep(.md-code-block:hover .md-code-block__copy) {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
:deep(.md-code-block__copy:hover) {
|
||||
opacity: 1;
|
||||
color: var(--el-color-primary);
|
||||
border-color: var(--el-color-primary);
|
||||
}
|
||||
|
||||
:deep(pre.hljs),
|
||||
:deep(pre) {
|
||||
overflow-x: auto;
|
||||
margin: 0;
|
||||
padding: 12px 14px;
|
||||
background: transparent;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
:deep(pre code) {
|
||||
display: block;
|
||||
padding: 0 !important;
|
||||
margin: 0;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--el-text-color-primary);
|
||||
font-size: 13px;
|
||||
line-height: 1.55;
|
||||
white-space: pre;
|
||||
font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, 'Liberation Mono', monospace;
|
||||
}
|
||||
|
||||
:deep(code) {
|
||||
font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, 'Liberation Mono', monospace;
|
||||
}
|
||||
|
||||
:deep(.hljs) {
|
||||
padding: 0 !important;
|
||||
background: transparent !important;
|
||||
}
|
||||
|
||||
:deep(:not(pre) > code) {
|
||||
display: inline;
|
||||
padding: 0.12em 0.32em;
|
||||
margin: 0;
|
||||
border-radius: 6px;
|
||||
background: rgba(175, 184, 193, 0.2);
|
||||
border: none;
|
||||
// 随正文颜色继承(原来硬编码 #24292f,深色下读不出来)
|
||||
font-size: 0.9em;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
:deep(p) {
|
||||
margin: 0 0 10px;
|
||||
}
|
||||
|
||||
:deep(p:last-child) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
:deep(ul),
|
||||
:deep(ol) {
|
||||
padding-left: 24px;
|
||||
margin: 0 0 10px;
|
||||
}
|
||||
|
||||
:deep(li + li) {
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
:deep(blockquote) {
|
||||
margin: 10px 0;
|
||||
padding: 8px 12px;
|
||||
border-left: 4px solid var(--el-color-primary-light-5);
|
||||
border-radius: 0 10px 10px 0;
|
||||
color: var(--el-text-color-secondary);
|
||||
background: var(--el-fill-color-lighter);
|
||||
}
|
||||
|
||||
:deep(.md-table-wrapper) {
|
||||
max-width: 100%;
|
||||
overflow-x: auto;
|
||||
margin: 12px 0;
|
||||
border: 1px solid var(--el-border-color);
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
:deep(table) {
|
||||
width: 100%;
|
||||
min-width: 520px;
|
||||
border-collapse: collapse;
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
:deep(th),
|
||||
:deep(td) {
|
||||
border: 1px solid var(--el-border-color);
|
||||
padding: 8px 10px;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
:deep(th) {
|
||||
background: var(--el-fill-color-light);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
:deep(tr:nth-child(even) td) {
|
||||
background: var(--el-fill-color-extra-light);
|
||||
}
|
||||
}
|
||||
|
||||
&__stream-cursor {
|
||||
display: inline-block;
|
||||
width: 8px;
|
||||
height: 18px;
|
||||
margin-left: 4px;
|
||||
border-radius: 4px;
|
||||
background: #60a5fa;
|
||||
vertical-align: middle;
|
||||
animation: stream-cursor-blink 1s steps(1) infinite;
|
||||
}
|
||||
|
||||
&__typing {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-top: 12px;
|
||||
// 屏蔽硬编码 #7b8794
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
&__typing-label {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
&__typing-dots {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
|
||||
i {
|
||||
display: inline-block;
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: #60a5fa;
|
||||
animation: typing-bounce 1.2s infinite ease-in-out;
|
||||
}
|
||||
|
||||
i:nth-child(2) {
|
||||
animation-delay: 0.15s;
|
||||
}
|
||||
|
||||
i:nth-child(3) {
|
||||
animation-delay: 0.3s;
|
||||
}
|
||||
}
|
||||
|
||||
&__actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
&--user &__actions {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
&__actions :deep(.el-button) {
|
||||
opacity: 0;
|
||||
transition: opacity 0.2s ease, transform 0.2s ease;
|
||||
transform: translateY(2px);
|
||||
}
|
||||
|
||||
&:hover &__actions :deep(.el-button) {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes typing-bounce {
|
||||
0%,
|
||||
80%,
|
||||
100% {
|
||||
transform: scale(0.72);
|
||||
opacity: 0.45;
|
||||
}
|
||||
|
||||
40% {
|
||||
transform: scale(1);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes stream-cursor-blink {
|
||||
0%,
|
||||
50% {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
50.01%,
|
||||
100% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,294 @@
|
||||
<template>
|
||||
<!-- 外观统一读 sidebarEffectiveCollapsed(偏好或视口降级都算折叠),不读偏好本身;
|
||||
「隐藏」不在这里处理 —— 由 ChatView 的 v-if 整棵卸载(占 0 宽)。 -->
|
||||
<div :class="['sidebar', { 'sidebar--collapsed': configStore.sidebarEffectiveCollapsed }]">
|
||||
<div class="sidebar__header">
|
||||
<el-button
|
||||
class="sidebar__create-btn"
|
||||
type="primary"
|
||||
:icon="Plus"
|
||||
@click="handleCreateSession"
|
||||
>
|
||||
<span v-if="!configStore.sidebarEffectiveCollapsed">新建对话</span>
|
||||
</el-button>
|
||||
<el-button class="sidebar__toggle-btn" circle @click="configStore.toggleSidebar()">
|
||||
<el-icon><Fold v-if="!configStore.sidebarEffectiveCollapsed" /><Expand v-else /></el-icon>
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<div v-if="!configStore.sidebarEffectiveCollapsed" class="sidebar__toolbar">
|
||||
<el-input
|
||||
v-model="searchKeyword"
|
||||
clearable
|
||||
size="small"
|
||||
placeholder="搜索会话"
|
||||
class="sidebar__search"
|
||||
>
|
||||
<template #prefix>
|
||||
<el-icon><Search /></el-icon>
|
||||
</template>
|
||||
</el-input>
|
||||
<el-popconfirm :width="220" title="确认清空全部历史会话吗?" @confirm="chatStore.clearAllSessions()">
|
||||
<template #reference>
|
||||
<el-button text type="danger">清空全部会话</el-button>
|
||||
</template>
|
||||
</el-popconfirm>
|
||||
</div>
|
||||
|
||||
<el-scrollbar class="sidebar__list">
|
||||
<div
|
||||
v-for="session in filteredSessions"
|
||||
:key="session.id"
|
||||
:class="['session-item', { 'session-item--active': session.id === chatStore.activeSessionId }]"
|
||||
@click="chatStore.switchSession(session.id)"
|
||||
>
|
||||
<div v-if="!configStore.sidebarEffectiveCollapsed" class="session-item__content">
|
||||
<div class="session-item__title-row">
|
||||
<el-tooltip :content="session.title" placement="top">
|
||||
<div class="session-item__title">{{ session.title }}</div>
|
||||
</el-tooltip>
|
||||
<el-button text size="small" @click.stop="startRename(session.id, session.title)">重命名</el-button>
|
||||
</div>
|
||||
<div class="session-item__time">创建于 {{ formatTime(session.createdAt) }}</div>
|
||||
</div>
|
||||
<div v-else class="session-item__collapsed-dot"></div>
|
||||
|
||||
<el-popconfirm v-if="!configStore.sidebarEffectiveCollapsed" :width="180" title="确认删除该会话吗?" @confirm="chatStore.deleteSession(session.id)">
|
||||
<template #reference>
|
||||
<el-button text type="danger" class="session-item__delete" @click.stop>
|
||||
<el-icon><Delete /></el-icon>
|
||||
</el-button>
|
||||
</template>
|
||||
</el-popconfirm>
|
||||
</div>
|
||||
<el-empty v-if="!configStore.sidebarEffectiveCollapsed && !filteredSessions.length" description="没有匹配的会话" :image-size="52" />
|
||||
</el-scrollbar>
|
||||
|
||||
<el-dialog v-model="renameDialogVisible" title="重命名会话" width="420px">
|
||||
<el-input v-model="renameTitle" maxlength="40" show-word-limit placeholder="请输入新的会话标题" />
|
||||
<template #footer>
|
||||
<el-button @click="renameDialogVisible = false">取消</el-button>
|
||||
<el-button type="primary" @click="submitRename">保存</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 主题开关:固定在侧栏右下角;折叠态只剩宽度 88px,这里只放图标,靠 tooltip 补文案 -->
|
||||
<div class="sidebar__footer">
|
||||
<el-tooltip :content="themeTooltip" placement="top">
|
||||
<el-button class="sidebar__theme-btn" circle @click="themeStore.toggleTheme()">
|
||||
<el-icon>
|
||||
<!-- 深色 → 太阳(切到浅色);浅色 → 月亮(切到深色) -->
|
||||
<Sunny v-if="themeStore.theme === 'dark'" />
|
||||
<Moon v-else />
|
||||
</el-icon>
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import { Delete, Expand, Fold, Moon, Plus, Search, Sunny } from '@element-plus/icons-vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { useChatStore } from '../stores/chat'
|
||||
import { useConfigStore } from '../stores/config'
|
||||
import { useThemeStore } from '../stores/theme'
|
||||
import { formatTime } from '../utils/common'
|
||||
|
||||
const chatStore = useChatStore()
|
||||
const configStore = useConfigStore()
|
||||
const themeStore = useThemeStore()
|
||||
|
||||
const renameDialogVisible = ref(false)
|
||||
const renameTitle = ref('')
|
||||
const targetSessionId = ref('')
|
||||
const searchKeyword = ref('')
|
||||
|
||||
const themeTooltip = computed(() => (themeStore.theme === 'dark' ? '切换到浅色模式' : '切换到深色模式'))
|
||||
|
||||
const filteredSessions = computed(() => {
|
||||
const keyword = searchKeyword.value.trim().toLowerCase()
|
||||
if (!keyword) return chatStore.sessions
|
||||
|
||||
return chatStore.sessions.filter((session) => session.title.toLowerCase().includes(keyword))
|
||||
})
|
||||
|
||||
function handleCreateSession(): void {
|
||||
chatStore.createSession()
|
||||
}
|
||||
|
||||
function startRename(sessionId: string, title: string): void {
|
||||
targetSessionId.value = sessionId
|
||||
renameTitle.value = title
|
||||
renameDialogVisible.value = true
|
||||
}
|
||||
|
||||
function submitRename(): void {
|
||||
const title = renameTitle.value.trim()
|
||||
if (!title) {
|
||||
ElMessage.warning('会话标题不能为空')
|
||||
return
|
||||
}
|
||||
|
||||
chatStore.renameSession(targetSessionId.value, title)
|
||||
renameDialogVisible.value = false
|
||||
ElMessage.success('会话标题已更新')
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.sidebar {
|
||||
width: 280px;
|
||||
// 侧栏宽度是布局契约(stores/config.ts 的 SIDEBAR_WIDTH_* 常量依赖这两个定值换算),
|
||||
// 不参与 flex 压缩 —— 否则覆盖态下侧栏被悄悄挤窄,常量就失真了。
|
||||
flex-shrink: 0;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
// 屏蔽 #f7f9fc / #e8ecf3:浅色下白一档(fill-blank),深色下 #141414 与页面底形成层次
|
||||
background: var(--el-fill-color-blank);
|
||||
border-right: 1px solid var(--el-border-color-lighter);
|
||||
transition: width 0.2s ease;
|
||||
|
||||
&--collapsed {
|
||||
width: 88px;
|
||||
}
|
||||
|
||||
&__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 16px;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
&__create-btn {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
&__toggle-btn {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
&--collapsed &__header {
|
||||
justify-content: center;
|
||||
flex-direction: column-reverse;
|
||||
}
|
||||
|
||||
&--collapsed &__create-btn {
|
||||
width: 56px;
|
||||
height: 40px;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
&--collapsed &__toggle-btn {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
&__toolbar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding: 0 16px 8px;
|
||||
}
|
||||
|
||||
&__search {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
&__list {
|
||||
flex: 1;
|
||||
padding: 0 12px 16px;
|
||||
}
|
||||
|
||||
&__footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
// 右下角:折叠态(88px)也保持右对齐,只显示图标
|
||||
justify-content: flex-end;
|
||||
padding: 12px 16px 16px;
|
||||
border-top: 1px solid var(--el-border-color-lighter);
|
||||
}
|
||||
|
||||
&__theme-btn {
|
||||
flex-shrink: 0;
|
||||
transition: background-color 0.2s ease, color 0.2s ease;
|
||||
}
|
||||
|
||||
&--collapsed &__footer {
|
||||
padding: 12px 12px 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.session-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 12px;
|
||||
margin-bottom: 10px;
|
||||
border-radius: 12px;
|
||||
// 屏蔽 #ffffff:深色下白卡过亮,改用 EP 填充色(浅色近白、深色比侧栏亮一档)
|
||||
background: var(--el-fill-color-light);
|
||||
cursor: pointer;
|
||||
border: 1px solid transparent;
|
||||
transition: background-color 0.18s ease, border-color 0.18s ease;
|
||||
|
||||
&:hover {
|
||||
background: var(--el-fill-color);
|
||||
}
|
||||
|
||||
// 放在 hover 之后并把 :hover 一起覆盖,避免 hover 把选中态底色盖掉(同权重后者胜)
|
||||
&--active,
|
||||
&--active:hover {
|
||||
// EP primary-light-9:浅色 #ecf5ff(与原值一致),深色是配套的暗蓝底
|
||||
border-color: var(--el-color-primary);
|
||||
background: var(--el-color-primary-light-9);
|
||||
}
|
||||
|
||||
.sidebar--collapsed & {
|
||||
justify-content: center;
|
||||
padding: 14px 8px;
|
||||
}
|
||||
|
||||
&__content {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
&__title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
&__title {
|
||||
flex: 1;
|
||||
font-size: 14px;
|
||||
color: var(--el-text-color-primary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
&__time {
|
||||
margin-top: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
|
||||
&__delete {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
&__collapsed-dot {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 999px;
|
||||
background: #409eff;
|
||||
box-shadow: 0 0 0 4px rgba(64, 158, 255, 0.15);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { AppConfig } from '../types'
|
||||
|
||||
export const STORAGE_KEYS = {
|
||||
chatSessions: 'ai-chat-sessions',
|
||||
activeSessionId: 'ai-chat-active-session-id',
|
||||
sidebarCollapsed: 'ai-chat-sidebar-collapsed',
|
||||
} as const
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ⚠️ Phase 1 临时硬编码:浏览器直连 one-api(经 SSH 隧道)。
|
||||
// 这是**明知故犯的临时状态,不是最终设计** —— 最终 key 必须待在服务端。
|
||||
// Phase 2 迁到同源 /Api/aiChat 时,这一整块连同 apiKey 一起删除。
|
||||
// 详见 AGENTS.md §2(阶段)与 §5(传输层接缝)。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* one-api 端点(绝对地址,经 SSH 隧道)。
|
||||
* 实际请求地址由 services/chat.ts 的 normalizeBaseUrl 补全为
|
||||
* http://127.0.0.1:3100/v1/chat/completions,与 .scratch/one-api/test-sse.sh 一致。
|
||||
*
|
||||
* 注意:走绝对地址时浏览器直接请求 3100,属于跨域,**Vite dev proxy 不参与**
|
||||
* (proxy 只拦截相对路径)。测试期能否通过取决于 one-api/nginx 是否放行预检。
|
||||
*/
|
||||
|
||||
export const DEFAULT_CONFIG: AppConfig = {
|
||||
baseUrl: '',
|
||||
apiKey: '',
|
||||
model: 'agnes-2.5-flash',
|
||||
temperature: 0.7,
|
||||
maxTokens: 2048,
|
||||
contextRounds: 6,
|
||||
systemPrompt: '你是一个专业、准确、友好的 AI 助手。',
|
||||
stream: true,
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
// ⚠️ 必须放在最前面:vue-router 会注册 visibilitychange 监听器,在页面隐藏时
|
||||
// 调用原生 history.replaceState,Edge 会因此把最小化的窗口拉回前台。
|
||||
// 本文件把那个原生调用拦掉。详见 utils/history-guard.ts 的注释。
|
||||
import './utils/history-guard'
|
||||
|
||||
import { createApp } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
// 按需样式:程序化导入的组件需要单独补 CSS(模板里的会自动 tree-shake)
|
||||
import 'element-plus/theme-chalk/el-message.css'
|
||||
import 'element-plus/theme-chalk/el-message-box.css'
|
||||
// Element Plus 暗色模式两步之一:引入暗色 CSS 变量(之二是给 <html> 加 dark 类,
|
||||
// 由 stores/theme.ts 的 applyTheme() 在 mount 之前完成,避免主题闪烁)
|
||||
import 'element-plus/theme-chalk/dark/css-vars.css'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import './styles/index.scss'
|
||||
import { useThemeStore } from './stores/theme'
|
||||
|
||||
const app = createApp(App)
|
||||
const pinia = createPinia()
|
||||
|
||||
app.use(pinia)
|
||||
app.use(router)
|
||||
|
||||
// 显式传 pinia:initTheme 在组件树之外执行,不依赖“已激活的 pinia”
|
||||
useThemeStore(pinia).initTheme()
|
||||
|
||||
app.mount('#app')
|
||||
@@ -0,0 +1,24 @@
|
||||
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
|
||||
import ChatView from '../views/ChatView.vue'
|
||||
// ⚠️ InitView 必须静态 import —— OnLoadEnd 只保证文档加载完;
|
||||
// 懒加载 chunk 是之后才下载执行的,那时 window.init 还没挂上,
|
||||
// native 的 executeScript 会静默失败。
|
||||
import InitView from '../views/InitView.vue'
|
||||
|
||||
// history 模式 + 真实路径 /chat(方案 §1:CEF 窗口访问 http://127.0.0.1:3100/chat)。
|
||||
// 代价:静态托管的服务器必须配 SPA fallback
|
||||
// nginx: location / { try_files $uri $uri/ /index.html; }
|
||||
// vite dev 自带 fallback,`pnpm dev` 下 /chat 可直接访问。
|
||||
const routes: RouteRecordRaw[] = [
|
||||
{ path: '/', redirect: '/init' },
|
||||
{ path: '/init', name: 'init', component: InitView },
|
||||
{ path: '/chat', name: 'chat', component: ChatView },
|
||||
{ path: '/:pathMatch(.*)*', redirect: '/chat' },
|
||||
]
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
routes,
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,227 @@
|
||||
import { ElMessage } from 'element-plus'
|
||||
import type { AppConfig, OpenAIMessage, RequestChatParams } from '../types'
|
||||
|
||||
/**
|
||||
* 客户端超时。
|
||||
*
|
||||
* 原值 60000(1 分钟) 偏短:策略代码输出经常超过 1 分钟,会被客户端主动 abort,
|
||||
* 表现为「话说一半就停了」。nginx 侧是 proxy_read_timeout 600s,
|
||||
* 这里留足余量但仍低于它,避免客户端比服务端先放弃。
|
||||
*/
|
||||
const REQUEST_TIMEOUT = 300000
|
||||
|
||||
interface OpenAIStreamDelta {
|
||||
choices?: Array<{
|
||||
delta?: {
|
||||
content?: string
|
||||
}
|
||||
message?: {
|
||||
content?: string
|
||||
}
|
||||
finish_reason?: string | null
|
||||
}>
|
||||
error?: {
|
||||
message?: string
|
||||
}
|
||||
}
|
||||
|
||||
function buildHeaders(apiKey: string): HeadersInit {
|
||||
return {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeBaseUrl(baseUrl: string): string {
|
||||
const normalized = baseUrl.trim().replace(/\/+$/, '')
|
||||
if (/\/chat\/completions$/i.test(normalized)) {
|
||||
return normalized
|
||||
}
|
||||
|
||||
const apiBase = /\/v\d+$/i.test(normalized) ? normalized : `${normalized}/v1`
|
||||
return `${apiBase}/chat/completions`
|
||||
}
|
||||
|
||||
function mapHttpError(status: number, text: string): string {
|
||||
if (status === 400) return text || '请求参数错误,请检查模型参数配置'
|
||||
if (status === 401) return '鉴权失败,请检查 API Key 是否正确'
|
||||
if (status === 403) return '当前密钥无访问权限,请检查接口授权'
|
||||
if (status === 404) return '接口地址错误,请检查 BaseURL 是否正确'
|
||||
if (status === 408) return '请求超时,请稍后重试'
|
||||
if (status === 429) return '请求超限,请稍后重试'
|
||||
if (status >= 500) return '服务端异常,请检查模型服务状态'
|
||||
return text || `请求失败,状态码:${status}`
|
||||
}
|
||||
|
||||
async function parseErrorResponse(response: Response): Promise<string> {
|
||||
try {
|
||||
const contentType = response.headers.get('content-type') || ''
|
||||
if (contentType.includes('application/json')) {
|
||||
const data = (await response.json()) as { error?: { message?: string }; message?: string }
|
||||
return data?.error?.message || data?.message || ''
|
||||
}
|
||||
|
||||
return (await response.text()).slice(0, 300)
|
||||
} catch (_error) {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
function createRequestPayload(config: AppConfig, messages: OpenAIMessage[]) {
|
||||
return {
|
||||
model: config.model,
|
||||
messages,
|
||||
temperature: Number(config.temperature),
|
||||
max_tokens: Number(config.maxTokens),
|
||||
stream: config.stream,
|
||||
}
|
||||
}
|
||||
|
||||
function emitFriendlyError(message: string): void {
|
||||
ElMessage.error(message)
|
||||
}
|
||||
|
||||
async function handleNormalResponse(response: Response, onMessage: RequestChatParams['onMessage']): Promise<string> {
|
||||
const data = (await response.json()) as OpenAIStreamDelta
|
||||
|
||||
if (data.error?.message) {
|
||||
throw new Error(data.error.message)
|
||||
}
|
||||
|
||||
const content = data?.choices?.[0]?.message?.content || ''
|
||||
if (!content) {
|
||||
throw new Error('模型返回内容为空,请检查模型名称或响应格式')
|
||||
}
|
||||
|
||||
onMessage(content, true)
|
||||
return content
|
||||
}
|
||||
|
||||
async function handleStreamResponse(response: Response, onMessage: RequestChatParams['onMessage']): Promise<string> {
|
||||
if (!response.body) {
|
||||
throw new Error('当前环境不支持流式响应')
|
||||
}
|
||||
|
||||
const reader = response.body.getReader()
|
||||
const decoder = new TextDecoder('utf-8')
|
||||
let buffer = ''
|
||||
let completeContent = ''
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
|
||||
buffer += decoder.decode(value, { stream: true })
|
||||
const segments = buffer.split('\n\n')
|
||||
buffer = segments.pop() || ''
|
||||
|
||||
for (const segment of segments) {
|
||||
const lines = segment.split('\n')
|
||||
for (const line of lines) {
|
||||
if (!line.startsWith('data:')) continue
|
||||
const rawData = line.replace(/^data:\s*/, '')
|
||||
if (rawData === '[DONE]') {
|
||||
onMessage(completeContent, true)
|
||||
return completeContent
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(rawData) as OpenAIStreamDelta
|
||||
|
||||
if (parsed.error?.message) {
|
||||
throw new Error(parsed.error.message)
|
||||
}
|
||||
|
||||
const delta = parsed?.choices?.[0]?.delta?.content || ''
|
||||
const finishReason = parsed?.choices?.[0]?.finish_reason
|
||||
|
||||
if (delta) {
|
||||
completeContent += delta
|
||||
onMessage(completeContent, false)
|
||||
}
|
||||
|
||||
if (finishReason) {
|
||||
onMessage(completeContent, true)
|
||||
return completeContent
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
throw error
|
||||
}
|
||||
console.warn('解析流式数据失败', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onMessage(completeContent, true)
|
||||
return completeContent
|
||||
}
|
||||
|
||||
export async function requestChatCompletion({ config, messages, signal, onMessage }: RequestChatParams): Promise<string> {
|
||||
const controller = new AbortController()
|
||||
const timeoutId = window.setTimeout(() => controller.abort(), REQUEST_TIMEOUT)
|
||||
|
||||
if (signal) {
|
||||
signal.addEventListener('abort', () => controller.abort(), { once: true })
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(normalizeBaseUrl(config.baseUrl), {
|
||||
method: 'POST',
|
||||
headers: buildHeaders(config.apiKey),
|
||||
body: JSON.stringify(createRequestPayload(config, messages)),
|
||||
signal: controller.signal,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await parseErrorResponse(response)
|
||||
const mappedMessage = mapHttpError(response.status, errorText)
|
||||
emitFriendlyError(mappedMessage)
|
||||
throw new Error(mappedMessage)
|
||||
}
|
||||
|
||||
if (!config.stream) {
|
||||
return await handleNormalResponse(response, onMessage)
|
||||
}
|
||||
|
||||
return await handleStreamResponse(response, onMessage)
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof DOMException && error.name === 'AbortError') {
|
||||
throw new Error('请求已停止')
|
||||
}
|
||||
|
||||
if (error instanceof TypeError && error.message.includes('Failed to fetch')) {
|
||||
const message = '网络异常、跨域受限或接口地址错误,请检查 BaseURL'
|
||||
emitFriendlyError(message)
|
||||
throw new Error(message)
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
if (error.message !== '请求已停止') {
|
||||
emitFriendlyError(error.message || '请求失败')
|
||||
}
|
||||
throw error
|
||||
}
|
||||
|
||||
emitFriendlyError('请求失败,请稍后重试')
|
||||
throw new Error('请求失败,请稍后重试')
|
||||
} finally {
|
||||
window.clearTimeout(timeoutId)
|
||||
}
|
||||
}
|
||||
|
||||
export async function testChatConnection(config: AppConfig, signal?: AbortSignal): Promise<void> {
|
||||
const testConfig: AppConfig = {
|
||||
...config,
|
||||
maxTokens: 1,
|
||||
stream: false,
|
||||
}
|
||||
|
||||
await requestChatCompletion({
|
||||
config: testConfig,
|
||||
messages: [{ role: 'user', content: 'ping' }],
|
||||
signal,
|
||||
onMessage: () => undefined,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { STORAGE_KEYS } from '../constants'
|
||||
import type { ChatMessage, ChatSession } from '../types'
|
||||
import { buildSessionTitle, generateId } from '../utils/common'
|
||||
import { loadLocalStorage, removeLocalStorage, saveLocalStorage } from '../utils/storage'
|
||||
|
||||
interface ChatStoreState {
|
||||
sessions: ChatSession[]
|
||||
activeSessionId: string
|
||||
isRequesting: boolean
|
||||
/** 流式期间有未落盘的改动,等 flushPersist() 统一写入 */
|
||||
persistPending: boolean
|
||||
}
|
||||
|
||||
function createEmptySession(): ChatSession {
|
||||
const timestamp = Date.now()
|
||||
return {
|
||||
id: generateId('session'),
|
||||
title: '新对话',
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
messages: [],
|
||||
}
|
||||
}
|
||||
|
||||
function sortSessionsByUpdatedAt(sessions: ChatSession[]): ChatSession[] {
|
||||
return [...sessions].sort((first, second) => second.updatedAt - first.updatedAt)
|
||||
}
|
||||
|
||||
function normalizeImportedMessage(message: Partial<ChatMessage>, index: number, sessionTimestamp: number): ChatMessage | null {
|
||||
if (!message || typeof message.content !== 'string') return null
|
||||
if (message.role !== 'system' && message.role !== 'user' && message.role !== 'assistant') return null
|
||||
|
||||
return {
|
||||
id: typeof message.id === 'string' && message.id ? message.id : generateId(`message-${index}`),
|
||||
role: message.role,
|
||||
content: message.content,
|
||||
createdAt: typeof message.createdAt === 'number' ? message.createdAt : sessionTimestamp,
|
||||
isLoading: false,
|
||||
error: Boolean(message.error),
|
||||
status: message.status,
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeImportedSession(session: Partial<ChatSession>, index: number): ChatSession | null {
|
||||
if (!session || !Array.isArray(session.messages)) return null
|
||||
|
||||
const timestamp = typeof session.createdAt === 'number' ? session.createdAt : Date.now()
|
||||
const messages = session.messages
|
||||
.map((message, messageIndex) => normalizeImportedMessage(message, messageIndex, timestamp))
|
||||
.filter((message): message is ChatMessage => Boolean(message))
|
||||
|
||||
const title = typeof session.title === 'string' && session.title.trim()
|
||||
? session.title.trim()
|
||||
: messages.find((item) => item.role === 'user')
|
||||
? buildSessionTitle(messages.find((item) => item.role === 'user')!.content)
|
||||
: '新对话'
|
||||
|
||||
const updatedAt = typeof session.updatedAt === 'number' ? session.updatedAt : timestamp
|
||||
|
||||
return {
|
||||
id: typeof session.id === 'string' && session.id ? session.id : generateId(`session-${index}`),
|
||||
title,
|
||||
createdAt: timestamp,
|
||||
updatedAt,
|
||||
messages,
|
||||
}
|
||||
}
|
||||
|
||||
export const useChatStore = defineStore('chat', {
|
||||
state: (): ChatStoreState => {
|
||||
const storedSessions = loadLocalStorage<ChatSession[]>(STORAGE_KEYS.chatSessions, [])
|
||||
const fallbackSession = createEmptySession()
|
||||
const sessions = storedSessions.length ? sortSessionsByUpdatedAt(storedSessions) : [fallbackSession]
|
||||
const storedActiveSessionId = loadLocalStorage<string>(STORAGE_KEYS.activeSessionId, sessions[0].id)
|
||||
const activeSession = sessions.find((session) => session.id === storedActiveSessionId) || sessions[0]
|
||||
|
||||
return {
|
||||
sessions,
|
||||
activeSessionId: activeSession.id,
|
||||
isRequesting: false,
|
||||
persistPending: false,
|
||||
}
|
||||
},
|
||||
getters: {
|
||||
activeSession(state): ChatSession {
|
||||
return state.sessions.find((session) => session.id === state.activeSessionId) || state.sessions[0]
|
||||
},
|
||||
},
|
||||
actions: {
|
||||
persistSessions() {
|
||||
this.sessions = sortSessionsByUpdatedAt(this.sessions)
|
||||
saveLocalStorage(STORAGE_KEYS.chatSessions, this.sessions)
|
||||
saveLocalStorage(STORAGE_KEYS.activeSessionId, this.activeSessionId)
|
||||
this.persistPending = false
|
||||
},
|
||||
/** 把流式期间攒下的改动落盘;没脏数据时什么都不做 */
|
||||
flushPersist() {
|
||||
if (!this.persistPending) return
|
||||
this.persistSessions()
|
||||
},
|
||||
createSession(): ChatSession {
|
||||
const newSession = createEmptySession()
|
||||
this.sessions.unshift(newSession)
|
||||
this.activeSessionId = newSession.id
|
||||
this.persistSessions()
|
||||
return newSession
|
||||
},
|
||||
switchSession(sessionId: string) {
|
||||
this.activeSessionId = sessionId
|
||||
this.persistSessions()
|
||||
},
|
||||
deleteSession(sessionId: string) {
|
||||
this.sessions = this.sessions.filter((session) => session.id !== sessionId)
|
||||
if (!this.sessions.length) {
|
||||
const newSession = createEmptySession()
|
||||
this.sessions = [newSession]
|
||||
this.activeSessionId = newSession.id
|
||||
} else if (this.activeSessionId === sessionId) {
|
||||
this.activeSessionId = this.sessions[0].id
|
||||
}
|
||||
this.persistSessions()
|
||||
},
|
||||
clearAllSessions() {
|
||||
const newSession = createEmptySession()
|
||||
this.sessions = [newSession]
|
||||
this.activeSessionId = newSession.id
|
||||
removeLocalStorage(STORAGE_KEYS.chatSessions)
|
||||
this.persistSessions()
|
||||
},
|
||||
clearCurrentSessionMessages() {
|
||||
const session = this.activeSession
|
||||
if (!session) return
|
||||
session.messages = []
|
||||
session.title = '新对话'
|
||||
session.updatedAt = Date.now()
|
||||
this.persistSessions()
|
||||
},
|
||||
appendMessage(message: ChatMessage) {
|
||||
const session = this.activeSession
|
||||
if (!session) return
|
||||
session.messages.push(message)
|
||||
session.updatedAt = Date.now()
|
||||
const firstUserMessage = session.messages.find((item) => item.role === 'user')
|
||||
if (firstUserMessage) {
|
||||
session.title = buildSessionTitle(firstUserMessage.content)
|
||||
}
|
||||
this.persistSessions()
|
||||
},
|
||||
updateMessage(messageId: string, partialMessage: Partial<ChatMessage>) {
|
||||
const targetSession = this.sessions.find((session) => session.messages.some((message) => message.id === messageId))
|
||||
if (!targetSession) return
|
||||
const targetMessage = targetSession.messages.find((message) => message.id === messageId)
|
||||
if (!targetMessage) return
|
||||
Object.assign(targetMessage, partialMessage)
|
||||
targetSession.updatedAt = Date.now()
|
||||
// ⚠️ 关键性能点:这里**不能**直接 persistSessions()。
|
||||
// 本方法每收到一个流式 delta 就被调一次,而落盘要做
|
||||
// JSON.stringify(全部会话) + localStorage.setItem(同步、阻塞主线程)。
|
||||
// 实测 ~200 片/秒 ⇒ 每秒 200 次全量序列化 ⇒ 流式会卡死。
|
||||
//
|
||||
// 只标脏,真正的写入交给调用方在流结束时 flushPersist():
|
||||
// 成功 / 用户中断 / 出错三个分支都会走到 ChatView 的 finally。
|
||||
//
|
||||
// ⚠️ 代价:流式进行中刷新或关闭窗口,这一轮的半截内容会丢。
|
||||
// 这是有意接受的取舍 —— 重新问一次即可,不值得为它引入节流。
|
||||
this.persistPending = true
|
||||
},
|
||||
removeMessage(messageId: string) {
|
||||
const targetSession = this.sessions.find((session) => session.messages.some((message) => message.id === messageId))
|
||||
if (!targetSession) return
|
||||
targetSession.messages = targetSession.messages.filter((message) => message.id !== messageId)
|
||||
const firstUserMessage = targetSession.messages.find((item) => item.role === 'user')
|
||||
targetSession.title = firstUserMessage ? buildSessionTitle(firstUserMessage.content) : '新对话'
|
||||
targetSession.updatedAt = Date.now()
|
||||
this.persistSessions()
|
||||
},
|
||||
renameSession(sessionId: string, title: string) {
|
||||
const targetSession = this.sessions.find((session) => session.id === sessionId)
|
||||
if (!targetSession) return
|
||||
targetSession.title = title.trim() || '新对话'
|
||||
targetSession.updatedAt = Date.now()
|
||||
this.persistSessions()
|
||||
},
|
||||
exportSessions() {
|
||||
return {
|
||||
exportedAt: Date.now(),
|
||||
sessions: this.sessions,
|
||||
activeSessionId: this.activeSessionId,
|
||||
}
|
||||
},
|
||||
importSessions(payload: { sessions?: Partial<ChatSession>[]; activeSessionId?: string }) {
|
||||
const importedSessions = Array.isArray(payload.sessions)
|
||||
? payload.sessions
|
||||
.map((session, index) => normalizeImportedSession(session, index))
|
||||
.filter((session): session is ChatSession => Boolean(session))
|
||||
: []
|
||||
|
||||
if (!importedSessions.length) {
|
||||
return false
|
||||
}
|
||||
|
||||
this.sessions = sortSessionsByUpdatedAt(importedSessions)
|
||||
this.activeSessionId = this.sessions.find((session) => session.id === payload.activeSessionId)?.id || this.sessions[0].id
|
||||
this.persistSessions()
|
||||
return true
|
||||
},
|
||||
setRequesting(status: boolean) {
|
||||
this.isRequesting = status
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,177 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { DEFAULT_CONFIG, STORAGE_KEYS } from '../constants'
|
||||
import type { AppConfig } from '../types'
|
||||
import { loadLocalStorage, saveLocalStorage } from '../utils/storage'
|
||||
|
||||
// —— 侧栏 / 聊天区布局尺寸(与 SidebarSessions.vue、ChatPanel.vue 的样式一一对应)——
|
||||
/** 展开态侧栏宽度(.sidebar { width: 280px }) */
|
||||
export const SIDEBAR_WIDTH_EXPANDED = 280
|
||||
/** 折叠态侧栏宽度(.sidebar--collapsed { width: 88px }) */
|
||||
export const SIDEBAR_WIDTH_COLLAPSED = 88
|
||||
/** 聊天面板最小宽度(.chat-panel { min-width: 480px }) */
|
||||
export const CHAT_PANEL_MIN_WIDTH = 480
|
||||
|
||||
/**
|
||||
* 动态阈值(不是固定值)—— 侧栏有三个视觉状态,判定阶梯按顺序命中即停:
|
||||
*
|
||||
* 1. 视口 ≥ 展开态可见阈值(280 + 480 = 760)→ 显示,尊重用户偏好(展开/折叠)
|
||||
* 2. 视口 ≥ 折叠态可见阈值( 88 + 480 = 568)→ 显示,强制折叠(偏好是展开也降级为折叠)
|
||||
* 3. 视口 < 568 → 隐藏(完全不渲染,占 0 宽)
|
||||
*
|
||||
* 隐藏不是第三个偏好,而是视口推导出来的事实:窗口变宽后按同一阶梯自然恢复,
|
||||
* 隐藏前的折叠/展开偏好(sidebarCollapsed)原样保留。
|
||||
* 568 同时是根元素 min-width(styles/index.scss)—— 可见侧栏的两种宽度都不会把布局挤爆。
|
||||
*/
|
||||
export const SIDEBAR_VISIBLE_EXPANDED_MIN_VIEWPORT = SIDEBAR_WIDTH_EXPANDED + CHAT_PANEL_MIN_WIDTH // 760
|
||||
export const SIDEBAR_VISIBLE_MIN_VIEWPORT = SIDEBAR_WIDTH_COLLAPSED + CHAT_PANEL_MIN_WIDTH // 568
|
||||
|
||||
/** 侧栏的三个视觉状态:expanded / collapsed 由偏好 + 视口共同决定,hidden 只由视口决定 */
|
||||
export type SidebarVisualState = 'expanded' | 'collapsed' | 'hidden'
|
||||
|
||||
interface ConfigStoreState {
|
||||
/**
|
||||
* 用户的折叠偏好 —— **唯一持久化的侧栏状态**(localStorage: ai-chat-sidebar-collapsed)。
|
||||
* 视口不会改它:窄视口只是暂时不按它渲染(降级为折叠或隐藏),
|
||||
* 窗口变宽后按判定阶梯原样恢复。
|
||||
*/
|
||||
sidebarCollapsed: boolean
|
||||
/**
|
||||
* 当前视口宽度(只在内存里,resize 时刷新,不落盘)。
|
||||
* 「是否隐藏」由它 + sidebarCollapsed 推导,不单独存第三份状态。
|
||||
*/
|
||||
viewportWidth: number
|
||||
}
|
||||
|
||||
function normalizeRequestBaseUrl(baseUrl: string): string {
|
||||
const normalized = baseUrl.trim().replace(/\/+$/, '')
|
||||
if (/\/chat\/completions$/i.test(normalized)) {
|
||||
return normalized.replace(/\/chat\/completions$/i, '')
|
||||
}
|
||||
|
||||
return /\/v\d+$/i.test(normalized) ? normalized : `${normalized}/v1`
|
||||
}
|
||||
|
||||
/**
|
||||
* 测量布局**实际可用**的视口宽度。
|
||||
*
|
||||
* 用 `document.documentElement.clientWidth` 而不是 `window.innerWidth`:
|
||||
* 后者包含垂直滚动条占用的宽度,会比真实可用宽度大 15~17px。
|
||||
* 两者在「无滚动条」时相等,所以平时看不出差别;但一旦出现滚动条,
|
||||
* 用 innerWidth 判定就会在临界点(760 / 568)上算多,导致侧栏被多留了几像素空间。
|
||||
*
|
||||
* 测量逻辑收在这里,调用方不需要也不应该知道用的是哪个 API。
|
||||
*/
|
||||
function getUsableViewportWidth(): number {
|
||||
if (typeof document === 'undefined') return SIDEBAR_VISIBLE_EXPANDED_MIN_VIEWPORT
|
||||
|
||||
const width = document.documentElement.clientWidth || window.innerWidth
|
||||
return width > 0 ? width : SIDEBAR_VISIBLE_EXPANDED_MIN_VIEWPORT
|
||||
}
|
||||
|
||||
export const useConfigStore = defineStore('config', {
|
||||
state: (): ConfigStoreState => {
|
||||
return {
|
||||
sidebarCollapsed: loadLocalStorage<boolean>(STORAGE_KEYS.sidebarCollapsed, false),
|
||||
// 用真实可用视口初始化:避免「首帧按 0 算出隐藏、mounted 才恢复」的侧栏闪现。
|
||||
viewportWidth: getUsableViewportWidth(),
|
||||
}
|
||||
},
|
||||
getters: {
|
||||
/**
|
||||
* 侧栏当前该长什么样(推导,不落盘)。判定阶梯按顺序命中即停:
|
||||
*
|
||||
* 1) 视口 ≥ 760:展开态放得下 → 显示侧栏,宽度尊重用户偏好(sidebarCollapsed)。
|
||||
* 2) 视口 ≥ 568:展开态放不下、折叠态放得下 → 显示侧栏但**强制折叠**
|
||||
* (偏好是「展开」也只是降级,不改偏好,窗口变宽自动还原成展开)。
|
||||
* 3) 视口 < 568:折叠态也放不下 → 隐藏,组件整棵不渲染、占 0 宽。
|
||||
*/
|
||||
sidebarVisualState(state): SidebarVisualState {
|
||||
if (state.viewportWidth >= SIDEBAR_VISIBLE_EXPANDED_MIN_VIEWPORT) {
|
||||
return state.sidebarCollapsed ? 'collapsed' : 'expanded'
|
||||
}
|
||||
|
||||
if (state.viewportWidth >= SIDEBAR_VISIBLE_MIN_VIEWPORT) {
|
||||
return 'collapsed'
|
||||
}
|
||||
|
||||
return 'hidden'
|
||||
},
|
||||
|
||||
/** 侧栏是否整体隐藏(不渲染、占 0 宽)。只由视口宽度决定。 */
|
||||
sidebarHidden(): boolean {
|
||||
return this.sidebarVisualState === 'hidden'
|
||||
},
|
||||
|
||||
/**
|
||||
* 渲染时要不要按折叠态(88px)画 —— 折叠偏好或视口不够宽(降级)都算。
|
||||
* 组件模板统一读这个,不要直接读 sidebarCollapsed(那是偏好,不等于当下外观)。
|
||||
*/
|
||||
sidebarEffectiveCollapsed(): boolean {
|
||||
return this.sidebarVisualState !== 'expanded'
|
||||
},
|
||||
|
||||
/**
|
||||
* 配置的唯一真源是 `constants/index.ts` 的 DEFAULT_CONFIG。
|
||||
*
|
||||
* ⚠️ 刻意**不读也不写 localStorage**:曾经这里会把 `ai-chat-app-config`
|
||||
* 覆盖在 DEFAULT_CONFIG 上面,导致改了 constants 却不生效,而 UI 入口
|
||||
* 又已隐藏、无法从界面修正。
|
||||
*
|
||||
* 当前形态是临时脚手架 —— baseUrl / apiKey 最终要从外部获取
|
||||
* (Phase 2 走服务端 /Api/aiChat,Phase 3 走 aiBridge.getAiConfig())。
|
||||
* 届时应改的是本 getter 的数据来源,而不是再加一层本地存储。
|
||||
*/
|
||||
effectiveConfig(): AppConfig {
|
||||
return { ...DEFAULT_CONFIG }
|
||||
},
|
||||
requestUrl(): string {
|
||||
return `${normalizeRequestBaseUrl(this.effectiveConfig.baseUrl)}/chat/completions`
|
||||
},
|
||||
},
|
||||
actions: {
|
||||
/**
|
||||
* 折叠 / 展开开关(点侧栏按钮)。开关按钮在侧栏内部,侧栏隐藏时按钮本来就不可见,
|
||||
* 所以这里只需要兜住「放不下还想展开」这一种情况。
|
||||
*
|
||||
* 行为:**拒绝展开并保持折叠 + 轻提示**。
|
||||
* 目标态是「展开」而视口 < 760 时,不改偏好、不落盘、侧栏也不动 ——
|
||||
* 绝不让侧栏(连同开关)当着用户的面消失;提示里带上具体宽度,用户知道该把窗口拉多宽。
|
||||
*
|
||||
* 返回值:true = 状态已切换;false = 被宽度拦下。
|
||||
*/
|
||||
toggleSidebar(): boolean {
|
||||
// 按「当前外观」反推目标:外观是折叠就想去展开,外观是展开就想去折叠。
|
||||
// 这样即使偏好是「展开」、只是被视口压成折叠(568~760 区间),点展开也是在表达
|
||||
// 「我想要展开」,会被宽度拦下而不是把偏好悄悄改成折叠。
|
||||
if (this.sidebarVisualState === 'hidden') {
|
||||
return false // 隐藏时开关不可见,理论到不了;防御性短路
|
||||
}
|
||||
|
||||
const wantExpanded = this.sidebarVisualState === 'collapsed'
|
||||
|
||||
if (wantExpanded && this.viewportWidth < SIDEBAR_VISIBLE_EXPANDED_MIN_VIEWPORT) {
|
||||
ElMessage.info(`窗口太窄,展开侧栏需要 ${SIDEBAR_VISIBLE_EXPANDED_MIN_VIEWPORT}px 宽度,请放大窗口后再试`)
|
||||
return false
|
||||
}
|
||||
|
||||
this.sidebarCollapsed = !wantExpanded
|
||||
saveLocalStorage(STORAGE_KEYS.sidebarCollapsed, this.sidebarCollapsed)
|
||||
return true
|
||||
},
|
||||
|
||||
/**
|
||||
* 视口变化时刷新 viewportWidth(由 ChatView 的 resize 监听调用)。
|
||||
*
|
||||
* 无参数 —— 宽度由 store 自己测量(见 getUsableViewportWidth),
|
||||
* 调用方不必知道该用 innerWidth 还是 clientWidth,改测量方式只需改一处。
|
||||
*
|
||||
* 只记事实、**不改 sidebarCollapsed** —— 隐藏/降级都是推导出来的(见 sidebarVisualState),
|
||||
* 所以不存在「自动折叠把用户偏好覆盖掉」的问题,也不再需要上一轮那套
|
||||
* auto-collapsed / manual-override 标记。窗口变宽时按判定阶梯自然恢复隐藏前的状态。
|
||||
*/
|
||||
updateViewportWidth(): void {
|
||||
this.viewportWidth = getUsableViewportWidth()
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,84 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import type { ThemeMode } from '../types'
|
||||
|
||||
/**
|
||||
* 主题是**纯 UI 偏好**,与 constants/index.ts 的 AI 配置(DEFAULT_CONFIG)无关,
|
||||
* 因此单独一个 store,不塞进 config store。
|
||||
*
|
||||
* 持久化规则(已定,勿改):
|
||||
* - localStorage key 固定 `ai-chat-theme`,值为裸字符串 'dark' | 'light'
|
||||
* —— 刻意不走 utils/storage 的 JSON 包装,保证 getItem 拿到的就是 dark/light
|
||||
* - key 不存在 → 跟随系统 prefers-color-scheme(系统切换时实时跟随)
|
||||
* - 用户手动切换过 → 写入 key,此后以用户选择为准,不再跟随系统
|
||||
*/
|
||||
const THEME_STORAGE_KEY = 'ai-chat-theme'
|
||||
|
||||
function readStoredTheme(): ThemeMode | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(THEME_STORAGE_KEY)
|
||||
return raw === 'dark' || raw === 'light' ? raw : null
|
||||
} catch (error) {
|
||||
console.error('读取主题本地存储失败', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function readSystemTheme(): ThemeMode {
|
||||
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
|
||||
return 'light'
|
||||
}
|
||||
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
|
||||
}
|
||||
|
||||
/** 系统主题监听只绑一次,防止 initTheme 被重复调用时叠加监听器 */
|
||||
let systemListenerBound = false
|
||||
|
||||
export const useThemeStore = defineStore('theme', {
|
||||
state: () => ({
|
||||
theme: 'light' as ThemeMode,
|
||||
/** key 不存在时为 true:跟随系统主题 */
|
||||
followSystem: true,
|
||||
}),
|
||||
actions: {
|
||||
/**
|
||||
* 启动时调用一次(main.ts,mount 之前,避免主题闪烁)。
|
||||
* 系统主题监听只绑一次,回调内部用 followSystem 决定是否生效。
|
||||
*/
|
||||
initTheme() {
|
||||
const stored = readStoredTheme()
|
||||
this.followSystem = stored === null
|
||||
this.theme = stored ?? readSystemTheme()
|
||||
this.applyTheme()
|
||||
|
||||
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return
|
||||
if (systemListenerBound) return
|
||||
systemListenerBound = true
|
||||
|
||||
const media = window.matchMedia('(prefers-color-scheme: dark)')
|
||||
media.addEventListener('change', (event) => {
|
||||
if (!this.followSystem) return
|
||||
this.theme = event.matches ? 'dark' : 'light'
|
||||
this.applyTheme()
|
||||
})
|
||||
},
|
||||
/** 把当前主题落到 <html class="dark">,Element Plus 暗色靠它生效 */
|
||||
applyTheme() {
|
||||
document.documentElement.classList.toggle('dark', this.theme === 'dark')
|
||||
},
|
||||
/** 用户手动切换:写入 key,从此不再跟随系统 */
|
||||
setTheme(mode: ThemeMode) {
|
||||
this.followSystem = false
|
||||
this.theme = mode
|
||||
try {
|
||||
localStorage.setItem(THEME_STORAGE_KEY, mode)
|
||||
} catch (error) {
|
||||
// 主题写失败不影响本次会话,只是下次打开回到跟随系统
|
||||
console.error('保存主题本地存储失败', error)
|
||||
}
|
||||
this.applyTheme()
|
||||
},
|
||||
toggleTheme() {
|
||||
this.setTheme(this.theme === 'dark' ? 'light' : 'dark')
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,157 @@
|
||||
:root {
|
||||
color-scheme: light;
|
||||
font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
||||
line-height: 1.5;
|
||||
font-weight: 400;
|
||||
// 屏蔽硬编码 #1f2937 / #eef3f9:回落到 Element Plus 变量(html.dark 下自动切深色)
|
||||
color: var(--el-text-color-primary);
|
||||
background: var(--el-bg-color-page);
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#app {
|
||||
margin: 0;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
// 浏览器窗口缩不下去的兜底:侧栏在窄视口会**整体隐藏**(不渲染、占 0 宽,
|
||||
// 见 stores/config.ts 的判定阶梯),所以最小视口只剩聊天面板本身:
|
||||
// CHAT_PANEL_MIN_WIDTH = 480px。视口 < 480 时布局不再压缩,而是横向溢出
|
||||
//(相当于窗口「不能再缩小」)。写在根元素 html 上保证视口级生效,
|
||||
// body 同步一条以防内联布局场景。
|
||||
min-width: 480px;
|
||||
}
|
||||
|
||||
body {
|
||||
// 原先的浅色渐变已移除:.chat-layout 是不透明满屏背景,body 渐变本来就盖在下面看不见,
|
||||
// 同时它在深色下会变成一块刺眼的浅底。
|
||||
background-color: var(--el-bg-color-page);
|
||||
}
|
||||
|
||||
button,
|
||||
input,
|
||||
textarea {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
#app {
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
|
||||
::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
border-radius: 999px;
|
||||
// 屏蔽硬编码 rgba(31, 41, 55, 0.18):深色下几乎不可见
|
||||
background: var(--el-fill-color);
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 深色模式下的代码高亮。
|
||||
// utils/markdown.ts 引的是 highlight.js 的 github.css(浅色主题),其中
|
||||
// .hljs-string 是深蓝 #032f62、.hljs 基色近黑 —— 直接落在深色代码块上读不出来。
|
||||
// 这里按 github-dark 的调色板覆盖(只在 html.dark 生效,浅色仍是 github.css 原样)。
|
||||
// ---------------------------------------------------------------------------
|
||||
html.dark {
|
||||
.message-item__markdown {
|
||||
.hljs {
|
||||
color: #c9d1d9;
|
||||
}
|
||||
|
||||
.hljs-doctag,
|
||||
.hljs-keyword,
|
||||
.hljs-meta .hljs-keyword,
|
||||
.hljs-template-tag,
|
||||
.hljs-template-variable,
|
||||
.hljs-type,
|
||||
.hljs-variable.language_ {
|
||||
color: #ff7b72;
|
||||
}
|
||||
|
||||
.hljs-title,
|
||||
.hljs-title.class_,
|
||||
.hljs-title.class_.inherited__,
|
||||
.hljs-title.function_ {
|
||||
color: #d2a8ff;
|
||||
}
|
||||
|
||||
.hljs-attr,
|
||||
.hljs-attribute,
|
||||
.hljs-literal,
|
||||
.hljs-meta,
|
||||
.hljs-number,
|
||||
.hljs-operator,
|
||||
.hljs-variable,
|
||||
.hljs-selector-attr,
|
||||
.hljs-selector-class,
|
||||
.hljs-selector-id {
|
||||
color: #79c0ff;
|
||||
}
|
||||
|
||||
.hljs-regexp,
|
||||
.hljs-string,
|
||||
.hljs-meta .hljs-string {
|
||||
color: #a5d6ff;
|
||||
}
|
||||
|
||||
.hljs-built_in,
|
||||
.hljs-symbol {
|
||||
color: #ffa657;
|
||||
}
|
||||
|
||||
.hljs-comment,
|
||||
.hljs-code,
|
||||
.hljs-formula {
|
||||
color: #8b949e;
|
||||
}
|
||||
|
||||
.hljs-name,
|
||||
.hljs-quote,
|
||||
.hljs-selector-tag,
|
||||
.hljs-selector-pseudo {
|
||||
color: #7ee787;
|
||||
}
|
||||
|
||||
.hljs-subst,
|
||||
.hljs-emphasis,
|
||||
.hljs-strong {
|
||||
color: #c9d1d9;
|
||||
}
|
||||
|
||||
.hljs-section {
|
||||
color: #1f6feb;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.hljs-bullet {
|
||||
color: #ffa657;
|
||||
}
|
||||
|
||||
.hljs-addition {
|
||||
color: #aff5b4;
|
||||
background-color: rgba(46, 160, 67, 0.15);
|
||||
}
|
||||
|
||||
.hljs-deletion {
|
||||
color: #ffdcd7;
|
||||
background-color: rgba(248, 81, 73, 0.15);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/** UI 主题偏好。与 constants/index.ts 的 AI 配置无关,不要混为一谈。 */
|
||||
export type ThemeMode = 'dark' | 'light'
|
||||
|
||||
export type MessageRole = 'system' | 'user' | 'assistant'
|
||||
export type MessageStatus = 'pending' | 'streaming' | 'success' | 'error' | 'stopped'
|
||||
|
||||
export interface ChatMessage {
|
||||
id: string
|
||||
role: MessageRole
|
||||
content: string
|
||||
createdAt: number
|
||||
isLoading?: boolean
|
||||
error?: boolean
|
||||
status?: MessageStatus
|
||||
}
|
||||
|
||||
export interface MessageActionPayload {
|
||||
messageId: string
|
||||
}
|
||||
|
||||
export interface ChatSession {
|
||||
id: string
|
||||
title: string
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
messages: ChatMessage[]
|
||||
}
|
||||
|
||||
export interface AppConfig {
|
||||
baseUrl: string
|
||||
apiKey: string
|
||||
model: string
|
||||
temperature: number
|
||||
maxTokens: number
|
||||
contextRounds: number
|
||||
systemPrompt: string
|
||||
stream: boolean
|
||||
}
|
||||
|
||||
export interface ExportedChatSessionsPayload {
|
||||
exportedAt: number
|
||||
sessions: ChatSession[]
|
||||
activeSessionId: string
|
||||
}
|
||||
|
||||
export interface OpenAIMessage {
|
||||
role: MessageRole
|
||||
content: string
|
||||
}
|
||||
|
||||
export interface SendMessagePayload {
|
||||
content: string
|
||||
}
|
||||
|
||||
export interface RequestChatParams {
|
||||
config: AppConfig
|
||||
messages: OpenAIMessage[]
|
||||
signal?: AbortSignal
|
||||
onMessage: (content: string, done: boolean) => void
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
export function generateId(prefix = 'id'): string {
|
||||
return `${prefix}-${Date.now()}-${Math.random().toString(16).slice(2, 10)}`
|
||||
}
|
||||
|
||||
export function formatTime(timestamp: number): string {
|
||||
const date = new Date(timestamp)
|
||||
const year = date.getFullYear()
|
||||
const month = `${date.getMonth() + 1}`.padStart(2, '0')
|
||||
const day = `${date.getDate()}`.padStart(2, '0')
|
||||
const hours = `${date.getHours()}`.padStart(2, '0')
|
||||
const minutes = `${date.getMinutes()}`.padStart(2, '0')
|
||||
return `${year}-${month}-${day} ${hours}:${minutes}`
|
||||
}
|
||||
|
||||
export function buildSessionTitle(message: string): string {
|
||||
const normalized = message.replace(/\s+/g, ' ').trim()
|
||||
if (!normalized) return '新对话'
|
||||
|
||||
return normalized.length > 20 ? `${normalized.slice(0, 20)}...` : normalized
|
||||
}
|
||||
|
||||
export function getErrorMessage(error: unknown): string {
|
||||
if (!error) return '未知错误'
|
||||
|
||||
if (error instanceof DOMException && error.name === 'AbortError') {
|
||||
return '请求已停止'
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
return error.message || '请求失败,请稍后重试'
|
||||
}
|
||||
|
||||
return '请求失败,请稍后重试'
|
||||
}
|
||||
|
||||
export function validateHttpUrl(url: string): boolean {
|
||||
try {
|
||||
const parsedUrl = new URL(url)
|
||||
return ['http:', 'https:'].includes(parsedUrl.protocol)
|
||||
} catch (_error) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* 页面处于隐藏状态时,拦截原生 `history.replaceState`。
|
||||
*
|
||||
* ── 起因 ────────────────────────────────────────────────────────────────
|
||||
* vue-router 4.6.4 在创建 history 时**无条件**注册(源码见
|
||||
* node_modules/vue-router/dist/vue-router.mjs 的 createRouterHistory,
|
||||
* 不受是否配置 `scrollBehavior` 影响):
|
||||
*
|
||||
* document.addEventListener('visibilitychange', beforeUnloadListener)
|
||||
*
|
||||
* 该监听器在每次「切标签 / 最小化窗口 / 切到后台」时执行:
|
||||
*
|
||||
* if (document.visibilityState === 'hidden') {
|
||||
* if (!history.state) return
|
||||
* history.replaceState({ ...state, scroll: getScroll() }, '')
|
||||
* }
|
||||
*
|
||||
* 而 Edge 对「文档处于 hidden 状态时写入 history」会做出反应 ——
|
||||
* **把最小化的窗口拉回前台**。表现为:功能完全正常、无任何报错或日志,
|
||||
* 但浏览器一最小化就立刻自动还原;无痕窗口不复现;换任何其他站点也不复现。
|
||||
*
|
||||
* 本项目并没有配置 `scrollBehavior`,这次写入完全无用,因此直接拦掉。
|
||||
*
|
||||
* ── 为什么拦在原语这一层,而不是拦 vue-router ───────────────────────────
|
||||
* vue-router 的 `u()` 照常运行、照常调用 replaceState;被替换的只是
|
||||
* `history.replaceState` 这个原生 API 本身 —— 最后一道边界。拦在原语上意味着
|
||||
* 无论将来 vue-router 换实现,还是我们自己写了别的代码想在页面隐藏时改动
|
||||
* history,都会被同样拦住。这才是要守住的规则本身:「页面不可见时不要改动
|
||||
* 浏览器历史记录」。
|
||||
*
|
||||
* ── ⚠️ Phase 3 接入 CEF 前必须保留本文件 ────────────────────────────────
|
||||
* CEF 窗口同样会跑 vue-router、同样会触发这条路径。桌面程序的窗口自己弹回
|
||||
* 前台是严重缺陷,不是观感问题,所以这个修复是 Phase 3 的前置条件。
|
||||
*
|
||||
* 排查过程见 `.scratch/改造计划.md`。
|
||||
*/
|
||||
|
||||
if (typeof window !== 'undefined' && typeof history !== 'undefined') {
|
||||
const originalReplaceState = history.replaceState.bind(history)
|
||||
|
||||
history.replaceState = function patchedReplaceState(
|
||||
state: Parameters<History['replaceState']>[0],
|
||||
unused: Parameters<History['replaceState']>[1],
|
||||
url?: Parameters<History['replaceState']>[2],
|
||||
): void {
|
||||
if (document.visibilityState === 'hidden') {
|
||||
// 页面不可见时改动 history 会让 Edge 把最小化的窗口拉回前台
|
||||
return
|
||||
}
|
||||
originalReplaceState(state, unused, url)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import MarkdownIt from 'markdown-it'
|
||||
import hljs from 'highlight.js/lib/core'
|
||||
import javascript from 'highlight.js/lib/languages/javascript'
|
||||
import json from 'highlight.js/lib/languages/json'
|
||||
import 'highlight.js/styles/github.css'
|
||||
|
||||
hljs.registerLanguage('javascript', javascript)
|
||||
hljs.registerLanguage('json', json)
|
||||
|
||||
const CODE_LANGUAGES = ['sql', 'javascript', 'typescript', 'java', 'python', 'json', 'html', 'css', 'bash', 'shell', 'vue', 'xml', 'yaml', 'markdown']
|
||||
const LANGUAGE_ALIASES: Record<string, string> = {
|
||||
js: 'javascript',
|
||||
jsx: 'javascript',
|
||||
ts: 'typescript',
|
||||
tsx: 'typescript',
|
||||
sh: 'bash',
|
||||
shell: 'bash',
|
||||
zsh: 'bash',
|
||||
yml: 'yaml',
|
||||
md: 'markdown',
|
||||
text: 'plaintext',
|
||||
}
|
||||
const CODE_FENCE_PATTERN = /```[\s\S]*?```/
|
||||
const CODE_FENCE_LINE_PATTERN = /^```/gm
|
||||
const SQL_KEYWORDS = /\b(select|insert|update|delete|create|alter|drop|from|where|join|group by|order by|limit)\b/i
|
||||
const CODE_STRUCTURE_PATTERN = /[{};<>]|\b(function|const|let|var|public|private|class|interface|return|import|export|try|catch|async|await)\b/
|
||||
|
||||
function escapeCodeHtml(code: string): string {
|
||||
return code
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
|
||||
function escapeAttribute(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
}
|
||||
|
||||
function normalizeLanguage(language = ''): string {
|
||||
const normalized = language.trim().toLowerCase()
|
||||
return LANGUAGE_ALIASES[normalized] || normalized || 'plaintext'
|
||||
}
|
||||
|
||||
function getDisplayLanguage(language: string): string {
|
||||
return language === 'plaintext' ? 'text' : language
|
||||
}
|
||||
|
||||
function detectCodeLanguage(content: string): string {
|
||||
const normalized = content.trim().toLowerCase()
|
||||
|
||||
if (SQL_KEYWORDS.test(normalized)) return 'sql'
|
||||
if (/^\s*[{[]/.test(content) && /[}\]]\s*$/.test(content)) return 'json'
|
||||
if (/<[a-z][\s\S]*?>/i.test(content)) return 'html'
|
||||
if (/\b(interface|type|implements|readonly|enum)\b/.test(normalized)) return 'typescript'
|
||||
if (/\b(system\.out\.println|public static void main|new \w+\()/i.test(content)) return 'java'
|
||||
if (/\b(def |import |from .+ import |print\()/i.test(content)) return 'python'
|
||||
if (/\b(const|let|var|function|=>|console\.log)\b/.test(normalized)) return 'javascript'
|
||||
if (/\b(selectors?|padding|margin|color|background|display|flex)\s*:/i.test(content)) return 'css'
|
||||
if (/^(npm|pnpm|yarn|git|curl|docker|cd|ls|dir)\b/im.test(content)) return 'bash'
|
||||
|
||||
return 'plaintext'
|
||||
}
|
||||
|
||||
function shouldRenderAsCode(content: string): boolean {
|
||||
const trimmed = content.trim()
|
||||
if (!trimmed || CODE_FENCE_PATTERN.test(trimmed)) return false
|
||||
|
||||
const lines = trimmed.split(/\r?\n/).filter((line) => line.trim())
|
||||
if (lines.length >= 2 && (SQL_KEYWORDS.test(trimmed) || CODE_STRUCTURE_PATTERN.test(trimmed))) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (lines.length === 1) {
|
||||
return /^(select|insert|update|delete)\b/i.test(trimmed) || /^[{[]/.test(trimmed)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
function normalizeMarkdownContent(content: string): string {
|
||||
if (!shouldRenderAsCode(content)) {
|
||||
return content
|
||||
}
|
||||
|
||||
const language = detectCodeLanguage(content)
|
||||
if (CODE_LANGUAGES.includes(language) || language === 'plaintext') {
|
||||
return `\n\n\`\`\`${language}\n${content.trim()}\n\`\`\`\n\n`
|
||||
}
|
||||
|
||||
return content
|
||||
}
|
||||
|
||||
function closeUnclosedCodeFence(content: string): string {
|
||||
const fenceCount = content.match(CODE_FENCE_LINE_PATTERN)?.length || 0
|
||||
return fenceCount % 2 === 1 ? `${content}\n\`\`\`` : content
|
||||
}
|
||||
|
||||
const markdown: MarkdownIt = new MarkdownIt({
|
||||
html: false,
|
||||
linkify: true,
|
||||
breaks: true,
|
||||
typographer: true,
|
||||
highlight(code: string, language: string): string {
|
||||
const normalizedLanguage = normalizeLanguage(language)
|
||||
const languageLabel = hljs.getLanguage(normalizedLanguage) ? normalizedLanguage : 'plaintext'
|
||||
const displayLanguage = getDisplayLanguage(languageLabel)
|
||||
const highlightedCode = hljs.getLanguage(languageLabel)
|
||||
? hljs.highlight(code, { language: languageLabel }).value
|
||||
: escapeCodeHtml(code)
|
||||
|
||||
return `
|
||||
<div class="md-code-block" data-language="${escapeAttribute(displayLanguage)}">
|
||||
<div class="md-code-block__toolbar">
|
||||
<span class="md-code-block__language">${escapeAttribute(displayLanguage)}</span>
|
||||
<button type="button" class="md-code-block__copy" aria-label="复制代码">复制代码</button>
|
||||
</div>
|
||||
<pre class="hljs"><code>${highlightedCode}</code></pre>
|
||||
</div>
|
||||
`
|
||||
},
|
||||
})
|
||||
|
||||
const defaultLinkOpenRenderer = markdown.renderer.rules.link_open
|
||||
markdown.renderer.rules.link_open = (tokens, index, options, env, self) => {
|
||||
const token = tokens[index]
|
||||
const hrefIndex = token.attrIndex('href')
|
||||
|
||||
if (hrefIndex >= 0) {
|
||||
token.attrSet('target', '_blank')
|
||||
token.attrSet('rel', 'noopener noreferrer')
|
||||
}
|
||||
|
||||
return defaultLinkOpenRenderer ? defaultLinkOpenRenderer(tokens, index, options, env, self) : self.renderToken(tokens, index, options)
|
||||
}
|
||||
|
||||
markdown.renderer.rules.table_open = () => '<div class="md-table-wrapper"><table>\n'
|
||||
markdown.renderer.rules.table_close = () => '</table></div>\n'
|
||||
|
||||
export function renderMarkdown(content = ''): string {
|
||||
const normalizedContent = normalizeMarkdownContent(content)
|
||||
return markdown.render(closeUnclosedCodeFence(normalizedContent))
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
function notifyStorageError(action: string, key: string, error: unknown): void {
|
||||
const isQuotaExceeded = error instanceof DOMException && (
|
||||
error.name === 'QuotaExceededError' ||
|
||||
error.name === 'NS_ERROR_DOM_QUOTA_REACHED' ||
|
||||
error.code === 22 ||
|
||||
error.code === 1014
|
||||
)
|
||||
|
||||
const message = isQuotaExceeded
|
||||
? '本地存储空间不足,保存失败。建议删除部分历史会话、减少图片附件或导出备份后清理数据。'
|
||||
: `${action}失败:${key}`
|
||||
|
||||
ElMessage.error(message)
|
||||
console.error(`${action}本地存储失败: ${key}`, error)
|
||||
}
|
||||
|
||||
export function loadLocalStorage<T>(key: string, defaultValue: T): T {
|
||||
try {
|
||||
const rawValue = localStorage.getItem(key)
|
||||
return rawValue ? (JSON.parse(rawValue) as T) : defaultValue
|
||||
} catch (error) {
|
||||
notifyStorageError('读取', key, error)
|
||||
return defaultValue
|
||||
}
|
||||
}
|
||||
|
||||
export function saveLocalStorage<T>(key: string, value: T): void {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(value))
|
||||
} catch (error) {
|
||||
notifyStorageError('保存', key, error)
|
||||
}
|
||||
}
|
||||
|
||||
export function removeLocalStorage(key: string): void {
|
||||
try {
|
||||
localStorage.removeItem(key)
|
||||
} catch (error) {
|
||||
notifyStorageError('删除', key, error)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
<template>
|
||||
<div class="chat-layout">
|
||||
<!-- 隐藏是推导出来的视口状态:窄到折叠态也放不下时整棵不渲染、占 0 宽,
|
||||
窗口变宽后按判定阶梯重新出现(stores/config.ts 的 sidebarHidden)。 -->
|
||||
<SidebarSessions v-if="!configStore.sidebarHidden" />
|
||||
|
||||
<div class="chat-layout__main">
|
||||
<div class="chat-layout__content">
|
||||
<ChatPanel
|
||||
:messages="chatMessages"
|
||||
@send="handleSendMessage"
|
||||
@stop="handleStopGenerate"
|
||||
@clear-session="handleClearCurrentSession"
|
||||
@delete-message="handleDeleteMessage"
|
||||
@resend-message="handleResendMessage"
|
||||
@regenerate-message="handleRegenerateMessage"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { useRouter } from 'vue-router'
|
||||
import ChatPanel from '../components/ChatPanel.vue'
|
||||
import SidebarSessions from '../components/SidebarSessions.vue'
|
||||
import type { ChatMessage, MessageActionPayload, OpenAIMessage, SendMessagePayload } from '../types'
|
||||
import { useChatStore } from '../stores/chat'
|
||||
import { useConfigStore } from '../stores/config'
|
||||
import { requestChatCompletion } from '../services/chat'
|
||||
import { generateId, validateHttpUrl } from '../utils/common'
|
||||
|
||||
const chatStore = useChatStore()
|
||||
const configStore = useConfigStore()
|
||||
const router = useRouter()
|
||||
const abortControllerRef = ref<AbortController | null>(null)
|
||||
|
||||
// 响应式约束:视口变化只负责通知 store,隐藏 / 降级为折叠由判定阶梯推导
|
||||
//(stores/config.ts 的 sidebarVisualState:≥760 尊重偏好、568~760 强制折叠、<568 隐藏)。
|
||||
// 用 store 状态驱动(而非纯 media query),保证开关按钮显示的状态与实际外观始终一致。
|
||||
// 宽度怎么测由 store 内部决定(clientWidth,非 innerWidth),这里不关心。
|
||||
function handleWindowResize(): void {
|
||||
configStore.updateViewportWidth()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
// 配置守卫:baseUrl / apiKey 任一为空说明未被 native 注入,跳回 /init 等待。
|
||||
const cfg = configStore.effectiveConfig
|
||||
if (!cfg.baseUrl || !cfg.apiKey) {
|
||||
router.replace('/init')
|
||||
return
|
||||
}
|
||||
|
||||
handleWindowResize()
|
||||
window.addEventListener('resize', handleWindowResize)
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('resize', handleWindowResize)
|
||||
if (abortControllerRef.value) {
|
||||
abortControllerRef.value.abort()
|
||||
}
|
||||
})
|
||||
const chatMessages = computed<ChatMessage[]>(() => chatStore.activeSession?.messages || [])
|
||||
const requestDebugSummary = computed(() => ({
|
||||
model: configStore.effectiveConfig.model,
|
||||
requestUrl: configStore.requestUrl,
|
||||
stream: configStore.effectiveConfig.stream,
|
||||
maxTokens: configStore.effectiveConfig.maxTokens,
|
||||
temperature: configStore.effectiveConfig.temperature,
|
||||
}))
|
||||
|
||||
function buildRequestMessages(userPayload: SendMessagePayload, excludedMessageIds: string[] = []): OpenAIMessage[] {
|
||||
const activeMessages = chatStore.activeSession?.messages || []
|
||||
const excludedIds = new Set(excludedMessageIds)
|
||||
const contextMessageCount = Math.max(Number(configStore.effectiveConfig.contextRounds) * 2, 0)
|
||||
const historyMessages = contextMessageCount
|
||||
? activeMessages
|
||||
.filter((message) => !excludedIds.has(message.id) && !message.isLoading && message.status !== 'error')
|
||||
.slice(-contextMessageCount)
|
||||
: []
|
||||
const requestMessages: OpenAIMessage[] = []
|
||||
|
||||
if (configStore.effectiveConfig.systemPrompt.trim()) {
|
||||
requestMessages.push({
|
||||
role: 'system',
|
||||
content: configStore.effectiveConfig.systemPrompt.trim(),
|
||||
})
|
||||
}
|
||||
|
||||
historyMessages.forEach((message) => {
|
||||
requestMessages.push({
|
||||
role: message.role,
|
||||
content: message.content,
|
||||
})
|
||||
})
|
||||
|
||||
requestMessages.push({
|
||||
role: 'user',
|
||||
content: userPayload.content,
|
||||
})
|
||||
|
||||
return requestMessages
|
||||
}
|
||||
|
||||
function validateRequestConfig(): boolean {
|
||||
const { baseUrl, apiKey, model } = configStore.effectiveConfig
|
||||
|
||||
if (!baseUrl.trim() || !apiKey.trim() || !model.trim()) {
|
||||
ElMessage.warning('请先在设置中完善 BaseURL、API Key 和模型名称配置')
|
||||
return false
|
||||
}
|
||||
|
||||
if (!validateHttpUrl(baseUrl)) {
|
||||
ElMessage.warning('请输入合法的 BaseURL 地址,必须以 http/https 开头')
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
function createAssistantPlaceholder(assistantMessageId: string): void {
|
||||
chatStore.appendMessage({
|
||||
id: assistantMessageId,
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
createdAt: Date.now(),
|
||||
isLoading: true,
|
||||
status: 'pending',
|
||||
})
|
||||
}
|
||||
|
||||
async function requestAssistantReply(payload: SendMessagePayload, excludedMessageIds: string[] = []): Promise<void> {
|
||||
if (!validateRequestConfig()) {
|
||||
return
|
||||
}
|
||||
|
||||
if (chatStore.isRequesting) {
|
||||
ElMessage.warning('当前已有请求进行中,请稍后再试')
|
||||
return
|
||||
}
|
||||
|
||||
const requestMessages = buildRequestMessages(payload, excludedMessageIds)
|
||||
const assistantMessageId = generateId('message')
|
||||
createAssistantPlaceholder(assistantMessageId)
|
||||
|
||||
chatStore.setRequesting(true)
|
||||
abortControllerRef.value = new AbortController()
|
||||
|
||||
try {
|
||||
if (import.meta.env.DEV) {
|
||||
console.groupCollapsed('[AI Request Debug]')
|
||||
console.log('config', requestDebugSummary.value)
|
||||
console.log('messages', requestMessages)
|
||||
console.groupEnd()
|
||||
}
|
||||
|
||||
await requestChatCompletion({
|
||||
config: configStore.effectiveConfig,
|
||||
messages: requestMessages,
|
||||
signal: abortControllerRef.value.signal,
|
||||
onMessage(partialContent, done) {
|
||||
chatStore.updateMessage(assistantMessageId, {
|
||||
content: partialContent,
|
||||
isLoading: !done,
|
||||
error: false,
|
||||
status: done ? 'success' : 'streaming',
|
||||
})
|
||||
},
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : '请求失败,请稍后重试'
|
||||
|
||||
if (message === '请求已停止') {
|
||||
const currentMessage = chatStore.sessions.flatMap((session) => session.messages).find((item) => item.id === assistantMessageId)
|
||||
if (!currentMessage?.content.trim()) {
|
||||
chatStore.removeMessage(assistantMessageId)
|
||||
} else {
|
||||
chatStore.updateMessage(assistantMessageId, {
|
||||
isLoading: false,
|
||||
error: false,
|
||||
status: 'stopped',
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
chatStore.updateMessage(assistantMessageId, {
|
||||
content: message,
|
||||
isLoading: false,
|
||||
error: true,
|
||||
status: 'error',
|
||||
})
|
||||
|
||||
await ElMessageBox.alert(message, '错误提示', {
|
||||
type: 'error',
|
||||
})
|
||||
} finally {
|
||||
abortControllerRef.value = null
|
||||
chatStore.setRequesting(false)
|
||||
// 流式期间只标脏不落盘(见 stores/chat.ts 的 PERSIST_THROTTLE_MS 注释)。
|
||||
// 这里统一落一次 —— 成功 / 失败 / 用户中断三个分支都会走到 finally
|
||||
//(catch 里 L234 的 return 同样会触发 finally)。
|
||||
chatStore.flushPersist()
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSendMessage(payload: SendMessagePayload): Promise<void> {
|
||||
if (!validateRequestConfig()) {
|
||||
return
|
||||
}
|
||||
|
||||
if (chatStore.isRequesting) {
|
||||
ElMessage.warning('当前已有请求进行中,请稍后再试')
|
||||
return
|
||||
}
|
||||
|
||||
const userMessageId = generateId('message')
|
||||
|
||||
chatStore.appendMessage({
|
||||
id: userMessageId,
|
||||
role: 'user',
|
||||
content: payload.content,
|
||||
createdAt: Date.now(),
|
||||
status: 'success',
|
||||
})
|
||||
|
||||
await requestAssistantReply(payload, [userMessageId])
|
||||
}
|
||||
|
||||
function handleStopGenerate(): void {
|
||||
if (abortControllerRef.value) {
|
||||
abortControllerRef.value.abort()
|
||||
abortControllerRef.value = null
|
||||
ElMessage.info('已停止本次生成')
|
||||
}
|
||||
chatStore.setRequesting(false)
|
||||
}
|
||||
|
||||
async function confirmDangerAction(message: string, title: string, confirmButtonText: string): Promise<boolean> {
|
||||
try {
|
||||
await ElMessageBox.confirm(message, title, {
|
||||
confirmButtonText,
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
customClass: 'chat-confirm-message-box',
|
||||
modalClass: 'chat-confirm-message-box__overlay',
|
||||
})
|
||||
return true
|
||||
} catch (_error) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function handleClearCurrentSession(): Promise<void> {
|
||||
if (chatStore.isRequesting) {
|
||||
ElMessage.warning('请求进行中,暂不支持清空当前会话')
|
||||
return
|
||||
}
|
||||
|
||||
if (!chatStore.activeSession?.messages.length) {
|
||||
ElMessage.info('当前会话暂无可清空的消息')
|
||||
return
|
||||
}
|
||||
|
||||
const confirmed = await confirmDangerAction('确认清空当前会话记录吗?清空后无法恢复。', '清空当前会话', '确认清空')
|
||||
if (!confirmed) return
|
||||
|
||||
chatStore.clearCurrentSessionMessages()
|
||||
ElMessage.success('当前会话记录已清空')
|
||||
}
|
||||
|
||||
async function handleDeleteMessage({ messageId }: MessageActionPayload): Promise<void> {
|
||||
if (chatStore.isRequesting) {
|
||||
ElMessage.warning('请求进行中,暂不支持删除消息')
|
||||
return
|
||||
}
|
||||
|
||||
const confirmed = await confirmDangerAction('确认删除这条消息吗?删除后无法恢复。', '删除消息', '确认删除')
|
||||
if (!confirmed) return
|
||||
|
||||
chatStore.removeMessage(messageId)
|
||||
ElMessage.success('消息已删除')
|
||||
}
|
||||
|
||||
async function handleResendMessage({ messageId }: MessageActionPayload): Promise<void> {
|
||||
if (chatStore.isRequesting) {
|
||||
ElMessage.warning('请求进行中,请稍后再试')
|
||||
return
|
||||
}
|
||||
|
||||
const targetMessage = chatStore.activeSession?.messages.find((item) => item.id === messageId)
|
||||
if (!targetMessage || targetMessage.role !== 'user') {
|
||||
ElMessage.warning('仅支持重发用户消息')
|
||||
return
|
||||
}
|
||||
|
||||
await requestAssistantReply(
|
||||
{
|
||||
content: targetMessage.content,
|
||||
},
|
||||
[targetMessage.id],
|
||||
)
|
||||
ElMessage.success('已重新发送该消息')
|
||||
}
|
||||
|
||||
async function handleRegenerateMessage({ messageId }: MessageActionPayload): Promise<void> {
|
||||
if (chatStore.isRequesting) {
|
||||
ElMessage.warning('请求进行中,请稍后再试')
|
||||
return
|
||||
}
|
||||
|
||||
const messages = chatStore.activeSession?.messages || []
|
||||
const assistantIndex = messages.findIndex((item) => item.id === messageId)
|
||||
if (assistantIndex === -1) {
|
||||
ElMessage.warning('未找到需要重新生成的消息')
|
||||
return
|
||||
}
|
||||
|
||||
const assistantMessage = messages[assistantIndex]
|
||||
if (assistantMessage.role !== 'assistant') {
|
||||
ElMessage.warning('仅支持重新生成 AI 回复')
|
||||
return
|
||||
}
|
||||
|
||||
const relatedUserMessage = [...messages.slice(0, assistantIndex)].reverse().find((item) => item.role === 'user')
|
||||
if (!relatedUserMessage) {
|
||||
ElMessage.warning('未找到关联的用户消息')
|
||||
return
|
||||
}
|
||||
|
||||
chatStore.removeMessage(messageId)
|
||||
await requestAssistantReply(
|
||||
{
|
||||
content: relatedUserMessage.content,
|
||||
},
|
||||
[relatedUserMessage.id],
|
||||
)
|
||||
ElMessage.success('已重新生成回复')
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
:global(.chat-confirm-message-box__overlay) {
|
||||
z-index: 20000 !important;
|
||||
}
|
||||
|
||||
:global(.chat-confirm-message-box) {
|
||||
z-index: 20001 !important;
|
||||
}
|
||||
|
||||
.chat-layout {
|
||||
display: flex;
|
||||
height: 100vh;
|
||||
background: var(--el-bg-color-page); // 屏蔽硬编码 #eef3f9:EP 变量随主题切换
|
||||
overflow-y: hidden;
|
||||
// 阶梯判定已保证「可见侧栏一定放得下」(展开 ≥760、折叠 ≥568、否则隐藏 0 宽),
|
||||
// 正常情况下这里不会溢出;auto 只是异常兜底(字体缩放、滚动条挤占等),
|
||||
// 万一挤出来给一条横向滚动条,而不是 hidden 把内容硬裁掉。
|
||||
overflow-x: auto;
|
||||
|
||||
&__main {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
&__content {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,52 @@
|
||||
<template>
|
||||
<div class="init-page">
|
||||
<div class="init-page__content">
|
||||
<div class="init-page__title">请登录</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { DEFAULT_CONFIG } from '../constants'
|
||||
import { validateHttpUrl } from '../utils/common'
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
// 全局 init(baseUrl, apiKey) —— 供 CEF 的 executeScript 直接调用(全局作用域求值)。
|
||||
// 模块作用域的函数在 executeScript 里不可见,因此必须挂到 window。
|
||||
declare global {
|
||||
interface Window {
|
||||
init: (baseUrl: string, apiKey: string) => void
|
||||
}
|
||||
}
|
||||
|
||||
window.init = function init(baseUrl: string, apiKey: string): void {
|
||||
if (!baseUrl || !apiKey) return // 两者都非空才接受
|
||||
if (!validateHttpUrl(baseUrl)) return // http/https 格式校验
|
||||
DEFAULT_CONFIG.baseUrl = baseUrl
|
||||
DEFAULT_CONFIG.apiKey = apiKey
|
||||
router.replace('/chat')
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.init-page {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100vh;
|
||||
background: var(--el-bg-color-page);
|
||||
}
|
||||
|
||||
.init-page__content {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.init-page__title {
|
||||
font-size: 32px;
|
||||
font-weight: 600;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
</style>
|
||||
Reference in New Issue
Block a user