Compare commits

..
2 Commits
Author SHA1 Message Date
Your Name 2530ddada6 更新 2026-07-22 09:49:30 +08:00
Your Name 7803c46b96 更新功能 2026-07-17 17:28:25 +08:00
24 changed files with 4462 additions and 481 deletions
+2
View File
@@ -0,0 +1,2 @@
logs/stability/
logs/conversation/
+25 -3
View File
@@ -159,6 +159,18 @@
<input v-model="form.seed_node" class="form-input" placeholder="自动识别,如 30:3" />
</div>
</div>
<div class="form-row-2">
<div class="form-group">
<label>img2img 重绘强度</label>
<input v-model.number="form.img2img_denoise" type="number" min="0.01" max="1" step="0.01" class="form-input" />
<p class="field-hint">默认 0.45越低越保留原图越高变化越明显</p>
</div>
<div class="form-group">
<label>inpaint 重绘强度</label>
<input v-model.number="form.inpaint_denoise" type="number" min="0.01" max="1" step="0.01" class="form-input" />
<p class="field-hint">默认 0.72仅作用于白色遮罩区域</p>
</div>
</div>
<p class="field-hint">
必须使用 <code>Save (API Format)</code> 导出的 JSON节点含 class_type
UI Format nodes/links导入后会秒结束且不出图
@@ -310,6 +322,8 @@ const form = reactive({
workflow_json: '',
prompt_node: '',
seed_node: '',
img2img_denoise: 0.45,
inpaint_denoise: 0.72,
refine_prompt: true,
system_prompt: ''
})
@@ -385,14 +399,16 @@ function onProviderChange() {
}
function parseExtraConfig(extra) {
if (!extra) return { workflow_json: '', prompt_node: '', seed_node: '', refine_prompt: true, system_prompt: '' }
if (!extra) return { workflow_json: '', prompt_node: '', seed_node: '', img2img_denoise: 0.45, inpaint_denoise: 0.72, refine_prompt: true, system_prompt: '' }
if (typeof extra === 'string') {
try { extra = JSON.parse(extra) } catch { return { workflow_json: '', prompt_node: '', seed_node: '', refine_prompt: true, system_prompt: '' } }
try { extra = JSON.parse(extra) } catch { return { workflow_json: '', prompt_node: '', seed_node: '', img2img_denoise: 0.45, inpaint_denoise: 0.72, refine_prompt: true, system_prompt: '' } }
}
return {
workflow_json: extra.workflow ? JSON.stringify(extra.workflow, null, 2) : '',
prompt_node: extra.prompt_node || '',
seed_node: extra.seed_node || '',
img2img_denoise: Number(extra.img2img_denoise ?? 0.45),
inpaint_denoise: Number(extra.inpaint_denoise ?? 0.72),
refine_prompt: extra.refine_prompt === undefined ? true : !!extra.refine_prompt,
system_prompt: extra.system_prompt || ''
}
@@ -437,6 +453,8 @@ function buildExtraConfig() {
}
if ((form.prompt_node || '').trim()) config.prompt_node = form.prompt_node.trim()
if ((form.seed_node || '').trim()) config.seed_node = form.seed_node.trim()
config.img2img_denoise = Math.max(0.01, Math.min(1, Number(form.img2img_denoise) || 0.45))
config.inpaint_denoise = Math.max(0.01, Math.min(1, Number(form.inpaint_denoise) || 0.72))
if ((form.system_prompt || '').trim()) config.system_prompt = form.system_prompt.trim()
config.refine_prompt = !!form.refine_prompt
return config
@@ -485,7 +503,7 @@ function openCreate() {
name: '', provider: 'openai', model_id: '', api_base_url: 'https://api.openai.com/v1',
api_key: '', max_tokens: 4096, temperature: 0.7, is_default: false, enabled: true, support_context: true, support_image: true,
frequency_penalty: 0, presence_penalty: 0,
workflow_json: '', prompt_node: '', seed_node: '', refine_prompt: true, system_prompt: ''
workflow_json: '', prompt_node: '', seed_node: '', img2img_denoise: 0.45, inpaint_denoise: 0.72, refine_prompt: true, system_prompt: ''
})
showModal.value = true
}
@@ -510,6 +528,8 @@ function openEdit(m) {
workflow_json: extra.workflow_json,
prompt_node: extra.prompt_node,
seed_node: extra.seed_node,
img2img_denoise: extra.img2img_denoise,
inpaint_denoise: extra.inpaint_denoise,
refine_prompt: extra.refine_prompt,
system_prompt: extra.system_prompt
})
@@ -540,6 +560,8 @@ async function saveModel() {
delete payload.workflow_json
delete payload.prompt_node
delete payload.seed_node
delete payload.img2img_denoise
delete payload.inpaint_denoise
delete payload.refine_prompt
delete payload.system_prompt
+27
View File
@@ -8,6 +8,7 @@
"name": "ai-chat-member",
"version": "1.0.0",
"dependencies": {
"@tabler/icons-vue": "^3.45.0",
"axios": "^1.7.9",
"dompurify": "^3.2.4",
"highlight.js": "^11.11.1",
@@ -865,6 +866,32 @@
"win32"
]
},
"node_modules/@tabler/icons": {
"version": "3.45.0",
"resolved": "https://registry.npmjs.org/@tabler/icons/-/icons-3.45.0.tgz",
"integrity": "sha512-jiATwV8+zGYLTZ7gMLGivCic+KtsMZXcDmufIG8umlLxoHhI6902hGYIEt0Oa9Y9SXblNzUlrisHm5jOFMxOQA==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/codecalm"
}
},
"node_modules/@tabler/icons-vue": {
"version": "3.45.0",
"resolved": "https://registry.npmjs.org/@tabler/icons-vue/-/icons-vue-3.45.0.tgz",
"integrity": "sha512-Q/cmDsx0zrzBScIL6Xxwevg7JqvkrteFW2R+NGTN9pwOrgJMzBLhyz/7ONvktjuwDn6eUKhFSM66CNAR8u3tRw==",
"license": "MIT",
"dependencies": {
"@tabler/icons": "3.45.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/codecalm"
},
"peerDependencies": {
"vue": ">=3.0.1"
}
},
"node_modules/@types/estree": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
+1
View File
@@ -9,6 +9,7 @@
"preview": "vite preview"
},
"dependencies": {
"@tabler/icons-vue": "^3.45.0",
"axios": "^1.7.9",
"dompurify": "^3.2.4",
"highlight.js": "^11.11.1",
+2
View File
@@ -1,6 +1,8 @@
<template>
<router-view />
<NotificationCenter />
</template>
<script setup>
import NotificationCenter from '@/components/NotificationCenter.vue'
</script>
+56 -3
View File
@@ -1,10 +1,34 @@
import axios from 'axios'
import { getGuestKey } from '@/utils/guestSession'
const api = axios.create({
baseURL: '/api',
timeout: 60000
})
let guestRenewal = null
async function renewGuestSession() {
const guestKey = getGuestKey()
if (!guestKey) throw new Error('游客身份已失效')
if (!guestRenewal) {
guestRenewal = axios.post('/api/auth/guest', { guest_key: guestKey })
.then(res => {
const data = res.data?.data
if (!data?.token) throw new Error('游客身份续期失败')
localStorage.setItem('token', data.token)
localStorage.setItem('auth_type', 'guest')
return data.token
})
.finally(() => {
guestRenewal = null
})
}
return guestRenewal
}
api.interceptors.request.use(config => {
const token = localStorage.getItem('token')
if (token) {
@@ -15,20 +39,49 @@ api.interceptors.request.use(config => {
api.interceptors.response.use(
res => res,
err => {
async err => {
if (axios.isCancel(err)) {
return Promise.reject(err)
}
const message = err.response?.data?.message || '请求失败'
const message = err.response?.data?.message || err.message || '请求失败'
if (err.response?.status === 401) {
const original = err.config || {}
const authType = localStorage.getItem('auth_type')
const requestUrl = String(original.url || '')
const isPublicAuthRequest = ['/auth/login', '/auth/register', '/auth/guest']
.some(path => requestUrl.includes(path))
if (isPublicAuthRequest) {
const wrapped = new Error(message)
wrapped.code = err.code
wrapped.status = 401
wrapped.detail = err.response?.data?.detail || ''
return Promise.reject(wrapped)
}
if (authType === 'guest' && !original._guestRetry) {
original._guestRetry = true
try {
const token = await renewGuestSession()
original.headers = original.headers || {}
original.headers.Authorization = `Bearer ${token}`
return api(original)
} catch {
// Fall through so the page can present a useful retry state.
}
}
localStorage.removeItem('token')
if (!window.location.pathname.includes('/login')) {
localStorage.removeItem('auth_type')
if (authType === 'account' && !window.location.pathname.includes('/login')) {
window.location.href = '/login'
}
}
const wrapped = new Error(message)
wrapped.code = err.code
wrapped.status = err.response?.status || null
wrapped.detail = err.response?.data?.detail || ''
return Promise.reject(wrapped)
}
)
+80 -39
View File
@@ -1,22 +1,29 @@
@import 'highlight.js/styles/github-dark.css';
@import 'highlight.js/styles/github.css';
:root {
--bg-primary: #212121;
--bg-secondary: #171717;
--bg-tertiary: #2f2f2f;
--bg-hover: #3a3a3a;
--text-primary: #ececec;
--text-secondary: #b4b4b4;
--text-muted: #8e8e8e;
--accent: #10a37f;
--accent-hover: #0d8a6a;
--border: #3a3a3a;
--danger: #ef4444;
--sidebar-width: 260px;
--header-height: 56px;
--input-max-width: 768px;
--radius: 12px;
--shadow: 0 4px 24px rgba(0, 0, 0, 0.3);
--bg-primary: #f5f7fb;
--bg-secondary: #ffffff;
--bg-tertiary: #f8fafc;
--bg-hover: #eef3f9;
--bg-soft: #f2f5f8;
--text-primary: #152033;
--text-secondary: #526077;
--text-muted: #7d899b;
--accent: #2d66da;
--accent-hover: #2458c4;
--accent-soft: #edf4ff;
--border: #e1e7ef;
--border-strong: #d4dce7;
--danger: #dc4c4c;
--sidebar-width: 268px;
--header-height: 66px;
--input-max-width: 920px;
--content-max-width: 1040px;
--radius: 18px;
--radius-sm: 12px;
--shadow: 0 18px 50px rgba(38, 59, 92, 0.08);
--shadow-soft: 0 8px 24px rgba(38, 59, 92, 0.06);
--shadow-composer: 0 14px 38px rgba(38, 59, 92, 0.09);
}
* {
@@ -27,10 +34,16 @@
html, body, #app {
height: 100%;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
min-height: 100dvh;
font-family: "Microsoft YaHei UI", "PingFang SC", "Segoe UI", sans-serif;
background: var(--bg-primary);
color: var(--text-primary);
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
}
body {
overflow: hidden;
}
a {
@@ -46,7 +59,16 @@ button {
font: inherit;
}
input, textarea {
button:focus-visible,
a:focus-visible,
select:focus-visible,
textarea:focus-visible,
input:focus-visible {
outline: 2px solid rgba(45, 102, 218, 0.72);
outline-offset: 2px;
}
input, textarea, select {
font: inherit;
color: inherit;
background: transparent;
@@ -54,47 +76,55 @@ input, textarea {
outline: none;
}
/* Scrollbar */
::-webkit-scrollbar {
width: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: var(--bg-hover);
border-radius: 3px;
background: #ced7e3;
border-radius: 999px;
}
/* Buttons */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 10px 20px;
border-radius: 8px;
border-radius: 999px;
font-size: 14px;
font-weight: 500;
transition: all 0.2s;
transition: color 0.16s ease, background 0.16s ease, border-color 0.16s ease, transform 0.16s ease;
}
.btn:active {
transform: scale(0.97);
}
.btn-primary {
background: var(--accent);
color: white;
}
.btn-primary:hover {
background: var(--accent-hover);
}
.btn-primary:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn-ghost {
background: transparent;
background: #fff;
color: var(--text-secondary);
border: 1px solid var(--border);
}
.btn-ghost:hover {
background: var(--bg-hover);
color: var(--text-primary);
@@ -103,11 +133,11 @@ input, textarea {
.btn-danger {
color: var(--danger);
}
.btn-danger:hover {
background: rgba(239, 68, 68, 0.1);
}
/* Form */
.form-group {
margin-bottom: 16px;
}
@@ -122,15 +152,16 @@ input, textarea {
.form-input {
width: 100%;
padding: 12px 16px;
background: var(--bg-tertiary);
background: #fff;
border: 1px solid var(--border);
border-radius: 8px;
border-radius: 14px;
font-size: 15px;
transition: border-color 0.2s;
transition: border-color 0.2s, box-shadow 0.2s;
}
.form-input:focus {
border-color: var(--accent);
box-shadow: 0 0 0 3px rgba(45, 102, 218, 0.11);
}
.form-error {
@@ -139,7 +170,6 @@ input, textarea {
margin-top: 12px;
}
/* Markdown content */
.markdown-body {
line-height: 1.7;
font-size: 15px;
@@ -149,11 +179,11 @@ input, textarea {
.markdown-body p {
margin-bottom: 12px;
}
.markdown-body p:last-child {
margin-bottom: 0;
}
/* 单个换行(非空行分段)时也留出呼吸空间,避免像 OCR 结果那样一行行挤在一起 */
.markdown-body br {
content: '';
display: block;
@@ -161,8 +191,9 @@ input, textarea {
}
.markdown-body pre {
background: var(--bg-secondary);
border-radius: 8px;
background: #f8fafc;
border: 1px solid var(--border);
border-radius: 14px;
padding: 16px;
overflow-x: auto;
margin: 12px 0;
@@ -174,9 +205,9 @@ input, textarea {
}
.markdown-body :not(pre) > code {
background: var(--bg-tertiary);
background: #eef2ff;
padding: 2px 6px;
border-radius: 4px;
border-radius: 6px;
}
.markdown-body ul, .markdown-body ol {
@@ -204,7 +235,7 @@ input, textarea {
}
.markdown-body th {
background: var(--bg-tertiary);
background: var(--bg-soft);
}
.markdown-body a {
@@ -216,12 +247,12 @@ input, textarea {
border-radius: 8px;
}
/* Overlay for mobile sidebar */
.sidebar-overlay {
display: none;
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
background: rgba(21, 32, 51, 0.34);
backdrop-filter: blur(2px);
z-index: 90;
}
@@ -230,3 +261,13 @@ input, textarea {
display: block;
}
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
scroll-behavior: auto !important;
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
}
}
File diff suppressed because it is too large Load Diff
+224 -118
View File
@@ -1,47 +1,50 @@
<template>
<aside class="sidebar" :class="{ open: chat.sidebarOpen }">
<aside class="sidebar" :class="{ open: chat.sidebarOpen }" aria-label="会话列表">
<div class="sidebar-top">
<select
v-if="settings.models.length"
class="model-select"
title="选择模型"
:value="chat.selectedModelId == null ? '' : String(chat.selectedModelId)"
@change="onModelChange"
>
<option
v-for="m in settings.models"
:key="m.id"
:value="String(m.id)"
>{{ m.name }}{{ m.provider === 'comfy' ? ' · 生图' : '' }}</option>
</select>
<button class="new-chat-btn" @click="handleNewChat">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M12 5v14M5 12h14"/>
</svg>
新对话
<div class="sidebar-brand">
<span class="brand-badge">AI</span>
<div class="brand-copy">
<strong>{{ settings.siteName || 'AI Chat' }}</strong>
<p>统一文本与图片创作</p>
</div>
<button class="sidebar-close" type="button" aria-label="关闭会话列表" @click="chat.closeSidebar">
<IconX :size="19" :stroke-width="1.8" />
</button>
</div>
<button class="new-chat-btn" type="button" @click="handleNewChat">
<IconPlus :size="18" :stroke-width="1.9" />
开始新对话
</button>
</div>
<div class="conversation-list">
<div class="conversation-heading">
<span>最近对话</span>
<span>{{ chat.conversations.length }}</span>
</div>
<div
v-for="conv in chat.conversations"
:key="conv.id"
class="conversation-item"
:class="{ active: conv.id === chat.currentId }"
:aria-current="conv.id === chat.currentId ? 'page' : undefined"
@click="selectConv(conv.id)"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/>
</svg>
<IconMessageCircle class="conversation-icon" :size="17" :stroke-width="1.7" />
<span class="conv-title">{{ conv.title }}</span>
<button class="delete-btn" @click.stop="handleDelete(conv.id)" title="删除">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M18 6L6 18M6 6l12 12"/>
</svg>
<button
class="delete-btn"
type="button"
:aria-label="`删除对话:${conv.title}`"
@click.stop="handleDelete(conv.id)"
>
<IconTrash :size="15" :stroke-width="1.8" />
</button>
</div>
<p v-if="!chat.conversations.length" class="empty-tip">暂无对点击上方开始</p>
<p v-if="!chat.conversations.length" class="empty-tip">还没有会先创建一个新对话</p>
</div>
<div class="sidebar-footer">
@@ -49,27 +52,27 @@
<div class="avatar">{{ avatarLetter }}</div>
<div class="user-meta">
<span class="user-name">{{ auth.user?.nickname || auth.user?.username }}</span>
<span class="user-level">{{ auth.user?.membership_name }}</span>
<span class="user-level">{{ auth.isGuest ? '游客模式 · 自动保存' : (auth.user?.membership_name || '普通用户') }}</span>
</div>
</div>
<a
v-if="auth.user?.role === 'admin'"
:href="adminUrl"
target="_blank"
class="admin-entry"
> 进入管理后台</a>
</div>
</aside>
</template>
<script setup>
import { computed, watch } from 'vue'
import IconMessageCircle from '@tabler/icons-vue/dist/esm/icons/IconMessageCircle.mjs'
import IconPlus from '@tabler/icons-vue/dist/esm/icons/IconPlus.mjs'
import IconTrash from '@tabler/icons-vue/dist/esm/icons/IconTrash.mjs'
import IconX from '@tabler/icons-vue/dist/esm/icons/IconX.mjs'
import { useAuthStore } from '@/stores/auth'
import { useChatStore } from '@/stores/chat'
import { useNotificationStore } from '@/stores/notification'
import { useSettingsStore } from '@/stores/settings'
const auth = useAuthStore()
const chat = useChatStore()
const notification = useNotificationStore()
const settings = useSettingsStore()
const avatarLetter = computed(() => {
@@ -77,8 +80,6 @@ const avatarLetter = computed(() => {
return name.charAt(0).toUpperCase()
})
const adminUrl = import.meta.env.VITE_ADMIN_URL || `${window.location.protocol}//${window.location.hostname}:5174`
watch(
() => settings.models,
(list) => {
@@ -90,28 +91,31 @@ watch(
{ immediate: true }
)
async function onModelChange(e) {
const value = e.target.value
async function handleNewChat() {
try {
await chat.setSelectedModel(value === '' ? null : Number(value))
await chat.createConversation(chat.selectedModelId)
chat.closeSidebar()
} catch (err) {
alert(err.message || '切换模型失败')
notification.error(err, { title: '创建对话失败' })
}
}
async function handleNewChat() {
await chat.createConversation(chat.selectedModelId)
chat.closeSidebar()
}
async function selectConv(id) {
await chat.selectConversation(id)
chat.closeSidebar()
try {
await chat.selectConversation(id)
chat.closeSidebar()
} catch (err) {
notification.error(err, { title: '加载对话失败' })
}
}
async function handleDelete(id) {
if (confirm('确定删除此对话?')) {
await chat.deleteConversation(id)
if (confirm('确定删除此对话')) {
try {
await chat.deleteConversation(id)
} catch (err) {
notification.error(err, { title: '删除对话失败' })
}
}
}
</script>
@@ -119,104 +123,196 @@ async function handleDelete(id) {
<style scoped>
.sidebar {
width: var(--sidebar-width);
background: var(--bg-secondary);
background: rgba(255, 255, 255, 0.94);
border-right: 1px solid var(--border);
display: flex;
flex-direction: column;
flex-shrink: 0;
transition: transform 0.3s ease;
transition: transform 0.24s cubic-bezier(0.16, 1, 0.3, 1);
backdrop-filter: blur(14px);
}
.sidebar-top {
padding: 12px;
padding: 16px 14px 12px;
display: flex;
flex-direction: column;
gap: 8px;
gap: 14px;
}
.model-select {
width: 100%;
padding: 8px 12px;
background: var(--bg-tertiary);
border: 1px solid var(--border);
border-radius: 8px;
font-size: 13px;
.sidebar-brand {
display: flex;
align-items: center;
gap: 10px;
min-height: 40px;
padding: 2px;
}
.brand-badge {
width: 38px;
height: 38px;
border-radius: 12px;
background: var(--accent-soft);
border: 1px solid #d9e6fb;
color: var(--accent);
display: flex;
align-items: center;
justify-content: center;
font-size: 14px;
font-weight: 700;
letter-spacing: -0.02em;
flex-shrink: 0;
}
.brand-copy {
min-width: 0;
flex: 1;
}
.sidebar-brand strong {
display: block;
overflow: hidden;
color: var(--text-primary);
font-size: 14px;
font-weight: 650;
line-height: 1.35;
text-overflow: ellipsis;
white-space: nowrap;
}
.sidebar-brand p {
margin-top: 2px;
color: var(--text-muted);
font-size: 11px;
line-height: 1.3;
}
.sidebar-close {
display: none;
width: 34px;
height: 34px;
align-items: center;
justify-content: center;
border-radius: 50%;
color: var(--text-secondary);
}
.new-chat-btn {
display: flex;
align-items: center;
gap: 8px;
justify-content: center;
gap: 7px;
width: 100%;
padding: 12px 16px;
background: var(--bg-tertiary);
border: 1px solid var(--border);
border-radius: 8px;
font-size: 14px;
color: var(--text-primary);
transition: background 0.2s;
min-height: 42px;
padding: 0 14px;
background: var(--accent);
border-radius: 12px;
color: #fff;
font-size: 13px;
font-weight: 600;
box-shadow: 0 7px 18px rgba(45, 102, 218, 0.2);
transition: background 0.16s ease, box-shadow 0.16s ease, transform 0.16s ease;
}
.new-chat-btn:hover {
background: var(--bg-hover);
background: var(--accent-hover);
box-shadow: 0 9px 22px rgba(45, 102, 218, 0.24);
}
.new-chat-btn:active {
transform: scale(0.98);
}
.conversation-list {
flex: 1;
overflow-y: auto;
padding: 4px 8px;
padding: 6px 9px 12px;
}
.conversation-heading {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 9px 7px;
color: var(--text-muted);
font-size: 11px;
}
.conversation-item {
position: relative;
display: flex;
align-items: center;
gap: 10px;
padding: 10px 12px;
border-radius: 8px;
gap: 9px;
min-height: 42px;
margin-bottom: 2px;
padding: 8px 8px 8px 10px;
border-radius: 10px;
cursor: pointer;
font-size: 14px;
color: var(--text-secondary);
transition: all 0.15s;
font-size: 13px;
transition: background 0.15s ease, color 0.15s ease;
}
.conversation-item:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.conversation-item.active {
background: var(--bg-tertiary);
color: var(--text-primary);
}
.conversation-item.active {
background: var(--accent-soft);
box-shadow: inset 3px 0 0 var(--accent);
color: var(--text-primary);
font-weight: 500;
}
.conversation-icon {
color: var(--text-muted);
flex-shrink: 0;
}
.conversation-item.active .conversation-icon {
color: var(--accent);
}
.conv-title {
flex: 1;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.delete-btn {
opacity: 0;
padding: 4px;
border-radius: 4px;
width: 28px;
height: 28px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
color: var(--text-muted);
opacity: 0;
flex-shrink: 0;
transition: background 0.15s ease, color 0.15s ease, opacity 0.15s ease;
}
.conversation-item:hover .delete-btn {
.conversation-item:hover .delete-btn,
.delete-btn:focus-visible {
opacity: 1;
}
.delete-btn:hover {
background: #fff0f0;
color: var(--danger);
background: rgba(239, 68, 68, 0.1);
}
.empty-tip {
text-align: center;
padding: 24px 16px;
font-size: 13px;
padding: 26px 18px;
color: var(--text-muted);
font-size: 12px;
line-height: 1.6;
text-align: center;
}
.sidebar-footer {
padding: 12px;
padding: 10px 12px 12px;
border-top: 1px solid var(--border);
}
@@ -224,63 +320,73 @@ async function handleDelete(id) {
display: flex;
align-items: center;
gap: 10px;
padding: 8px;
padding: 6px;
}
.avatar {
width: 32px;
height: 32px;
border-radius: 50%;
background: var(--accent);
width: 34px;
height: 34px;
border-radius: 11px;
background: #eef1f6;
color: var(--text-primary);
display: flex;
align-items: center;
justify-content: center;
font-size: 14px;
font-weight: 600;
color: white;
font-size: 13px;
font-weight: 650;
flex-shrink: 0;
}
.user-meta {
display: flex;
flex-direction: column;
min-width: 0;
}
.user-name {
font-size: 14px;
font-weight: 500;
overflow: hidden;
color: var(--text-primary);
font-size: 13px;
font-weight: 550;
text-overflow: ellipsis;
white-space: nowrap;
}
.user-level {
font-size: 12px;
margin-top: 2px;
color: var(--text-muted);
}
.admin-entry {
display: block;
margin-top: 8px;
padding: 10px 12px;
text-align: center;
font-size: 13px;
color: var(--accent);
background: rgba(16, 163, 127, 0.1);
border-radius: 8px;
text-decoration: none;
}
.admin-entry:hover {
background: rgba(16, 163, 127, 0.2);
font-size: 11px;
}
@media (max-width: 768px) {
.sidebar {
position: fixed;
top: 0;
left: 0;
bottom: 0;
inset: 0 auto 0 0;
z-index: 100;
width: min(84vw, 304px);
transform: translateX(-100%);
box-shadow: 20px 0 50px rgba(21, 32, 51, 0.14);
}
.sidebar.open {
transform: translateX(0);
}
.sidebar-close {
display: flex;
}
.delete-btn {
opacity: 0.68;
}
}
@media (prefers-reduced-motion: reduce) {
.sidebar,
.new-chat-btn,
.conversation-item,
.delete-btn {
transition: none;
}
}
</style>
File diff suppressed because one or more lines are too long
+606 -73
View File
@@ -1,19 +1,28 @@
<template>
<div class="message" :class="message.role">
<div class="message-avatar">
{{ message.role === 'user' ? 'U' : 'AI' }}
<div class="message" :class="[message.role, { streaming: isStreaming }]">
<div class="message-avatar" aria-hidden="true">
<IconUser v-if="message.role === 'user'" :size="16" :stroke-width="1.8" />
<IconSparkles v-else :size="16" :stroke-width="1.8" />
</div>
<div class="message-body">
<!-- 附件 -->
<div v-if="attachments.length" class="attachments">
<div ref="messageBodyRef" class="message-body" :class="{ 'wide-image-message': isAssistantImageGrid || showImageSkeleton }">
<div v-if="showImageSkeleton" class="image-loading-grid" aria-label="正在生成四张图片">
<span class="generation-progress"><IconSparkles :size="15" :stroke-width="1.8" /> {{ generationProgress }}%</span>
<i v-for="index in 4" :key="index" />
</div>
<div v-if="attachments.length" class="attachments" :class="{ 'image-grid': isAssistantImageGrid }">
<template v-for="(att, i) in attachments" :key="i">
<img
v-if="att?.type === 'image' && features.image && !brokenImages[i]"
:src="att.url"
:alt="att.name"
:alt="att.name || '生成图片'"
class="att-image"
role="button"
tabindex="0"
:aria-label="`放大查看${att.name || '图片'}`"
@error="markBroken(i)"
@click="previewImage(att.url)"
@click="previewImage(att)"
@keydown.enter="previewImage(att)"
@keydown.space.prevent="previewImage(att)"
/>
<a
v-else-if="att?.type === 'image'"
@@ -22,7 +31,8 @@
rel="noopener"
class="att-document"
>
🖼 {{ att.name || '图片' }}点击打开
<IconPhoto :size="17" :stroke-width="1.8" />
{{ att.name || '打开图片' }}
</a>
<video
v-else-if="att?.type === 'video' && features.video"
@@ -40,26 +50,64 @@
v-else-if="att?.type === 'document' && features.document"
:href="att.url"
target="_blank"
rel="noopener"
class="att-document"
>
{{ documentIcon(att) }} {{ att.name }} ({{ formatFileSize(att.size) }})
<IconFileText :size="17" :stroke-width="1.8" />
<span class="document-name">{{ att.name }}</span>
<span class="document-size">{{ formatFileSize(att.size) }}</span>
</a>
</template>
</div>
<!-- 文本内容 -->
<div
v-if="message.content"
class="message-content"
:class="{ 'markdown-body': useMarkdown }"
v-html="renderedContent"
/>
<div
v-if="(message.content || firstImage) && !isStreaming"
class="message-actions"
:class="{ 'has-image': firstImage }"
>
<button
v-if="firstImage"
class="message-action-btn image-edit-btn"
type="button"
aria-label=" AI 图片工作台中编辑"
@click="previewImage(firstImage)"
>
<IconEdit :size="15" :stroke-width="1.8" />
<span>AI 编辑</span>
</button>
<button
v-if="message.content || firstImage"
class="message-action-btn"
type="button"
:aria-label="copied ? '消息图文内容已复制' : '复制消息图文内容'"
@click="copyContent"
>
<IconCheck v-if="copied" :size="15" :stroke-width="2" />
<IconCopy v-else :size="15" :stroke-width="1.8" />
<span>{{ copied ? '已复制' : '复制' }}</span>
</button>
</div>
</div>
</div>
</template>
<script setup>
import { computed, reactive } from 'vue'
import { computed, reactive, ref, onBeforeUnmount, watch } from 'vue'
import IconCheck from '@tabler/icons-vue/dist/esm/icons/IconCheck.mjs'
import IconCopy from '@tabler/icons-vue/dist/esm/icons/IconCopy.mjs'
import IconFileText from '@tabler/icons-vue/dist/esm/icons/IconFileText.mjs'
import IconEdit from '@tabler/icons-vue/dist/esm/icons/IconEdit.mjs'
import IconPhoto from '@tabler/icons-vue/dist/esm/icons/IconPhoto.mjs'
import IconSparkles from '@tabler/icons-vue/dist/esm/icons/IconSparkles.mjs'
import IconUser from '@tabler/icons-vue/dist/esm/icons/IconUser.mjs'
import { useNotificationStore } from '@/stores/notification'
import { useSettingsStore } from '@/stores/settings'
import { renderMarkdown, formatFileSize } from '@/utils/markdown'
@@ -67,23 +115,61 @@ const props = defineProps({
message: { type: Object, required: true },
isStreaming: Boolean
})
const emit = defineEmits(['preview-image'])
const settings = useSettingsStore()
const notification = useNotificationStore()
const features = computed(() => settings.features)
const copied = ref(false)
const messageBodyRef = ref(null)
const generationProgress = ref(4)
const fourImageLoading = ref(false)
let copiedTimer = null
let progressTimer = null
onBeforeUnmount(() => {
if (copiedTimer) clearTimeout(copiedTimer)
if (progressTimer) clearInterval(progressTimer)
})
const attachments = computed(() => {
const raw = props.message.attachments
const list = Array.isArray(raw) ? raw : (raw && typeof raw === 'object' ? Object.values(raw) : [])
return list.filter(att => att && typeof att === 'object')
return list.filter(att => att && typeof att === 'object' && !att.hidden)
})
const firstImage = computed(() => attachments.value.find(att => att?.type === 'image' && att?.url) || null)
const imageAttachments = computed(() => attachments.value.filter(att => att?.type === 'image' && att?.url))
const isAssistantImageGrid = computed(() => props.message.role === 'assistant' && imageAttachments.value.length >= 2)
const pendingImageCount = computed(() => Number(props.message.pending_image_count || 0))
const showImageSkeleton = computed(() => fourImageLoading.value && !imageAttachments.value.length)
function documentIcon(att) {
const name = (att?.name || '').toLowerCase()
const mime = att?.mime || ''
if (name.endsWith('.pdf') || mime.includes('pdf')) return '📕'
if (name.endsWith('.doc') || name.endsWith('.docx') || mime.includes('word')) return '📘'
return '📄'
}
watch(
() => [props.isStreaming, props.message.pending_job, pendingImageCount.value, props.message.content, imageAttachments.value.length],
([streaming, pending, count, content, images]) => {
if (images) {
fourImageLoading.value = false
return
}
if ((pending && Number(count) >= 4) || (streaming && /正在生成\s*4\s*张图片|正在生成图片|图片生成中/u.test(String(content || '')))) {
fourImageLoading.value = true
return
}
if (!pending && !streaming) fourImageLoading.value = false
},
{ immediate: true }
)
watch(showImageSkeleton, active => {
if (progressTimer) {
clearInterval(progressTimer)
progressTimer = null
}
if (!active) return
generationProgress.value = 4
progressTimer = setInterval(() => {
generationProgress.value = Math.min(92, generationProgress.value + Math.max(1, Math.round((94 - generationProgress.value) * 0.08)))
}, 800)
}, { immediate: true })
const useMarkdown = computed(() => {
return features.value.markdown && props.message.role === 'assistant'
@@ -109,8 +195,250 @@ function markBroken(index) {
brokenImages[index] = true
}
function previewImage(url) {
window.open(url, '_blank')
function previewImage(attachment) {
if (!attachment?.url) return
emit('preview-image', {
url: attachment.url,
name: attachment.name || '图片预览'
})
}
const COPY_STYLE_PROPERTIES = [
'background-color', 'border', 'border-collapse', 'border-radius', 'box-shadow',
'color', 'display', 'font-family', 'font-size', 'font-style', 'font-weight',
'height', 'letter-spacing', 'line-height', 'list-style-position', 'list-style-type',
'margin', 'margin-bottom', 'margin-left', 'margin-right', 'margin-top', 'max-height',
'max-width', 'min-width', 'padding', 'padding-bottom', 'padding-left', 'padding-right',
'padding-top', 'text-align', 'text-decoration', 'vertical-align', 'white-space', 'width'
]
function inlineCopyStyles(source, clone) {
if (!(source instanceof Element) || !(clone instanceof Element)) return
const computedStyle = window.getComputedStyle(source)
COPY_STYLE_PROPERTIES.forEach(property => {
const value = computedStyle.getPropertyValue(property)
if (value) clone.style.setProperty(property, value)
})
clone.removeAttribute('class')
clone.removeAttribute('role')
clone.removeAttribute('tabindex')
clone.removeAttribute('aria-label')
if (clone instanceof HTMLImageElement) {
const rect = source.getBoundingClientRect()
if (rect.width > 0) clone.style.width = `${Math.round(rect.width)}px`
clone.style.height = 'auto'
clone.style.cursor = 'default'
}
const sourceChildren = Array.from(source.children)
const cloneChildren = Array.from(clone.children)
sourceChildren.forEach((child, index) => inlineCopyStyles(child, cloneChildren[index]))
}
function blobToDataUrl(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => resolve(String(reader.result || ''))
reader.onerror = () => reject(reader.error || new Error('图片读取失败'))
reader.readAsDataURL(blob)
})
}
async function fetchImageBlob(url) {
const response = await fetch(url, { credentials: 'include' })
if (!response.ok) throw new Error(`图片读取失败(${response.status}`)
const blob = await response.blob()
if (!blob.type.startsWith('image/')) throw new Error('附件不是图片')
return blob
}
function imageBlobToPng(blob) {
if (blob.type === 'image/png') return Promise.resolve(blob)
return new Promise((resolve, reject) => {
const image = new Image()
const objectUrl = URL.createObjectURL(blob)
image.onload = () => {
const canvas = document.createElement('canvas')
canvas.width = image.naturalWidth
canvas.height = image.naturalHeight
const context = canvas.getContext('2d')
if (!context) {
URL.revokeObjectURL(objectUrl)
reject(new Error('浏览器无法转换图片'))
return
}
context.drawImage(image, 0, 0)
URL.revokeObjectURL(objectUrl)
canvas.toBlob(result => {
if (result) resolve(result)
else reject(new Error('浏览器无法转换图片'))
}, 'image/png')
}
image.onerror = () => {
URL.revokeObjectURL(objectUrl)
reject(new Error('图片解码失败'))
}
image.src = objectUrl
})
}
function prepareRichCopyPayload() {
const sourceBody = messageBodyRef.value
const container = document.createElement('div')
container.setAttribute('data-ai-chat-message', '')
container.style.cssText = 'max-width:720px;color:#1f2937;font-family:Arial,"Microsoft YaHei",sans-serif;font-size:15px;line-height:1.75;'
if (sourceBody) {
Array.from(sourceBody.children).forEach(source => {
if (!source.classList.contains('attachments') && !source.classList.contains('message-content')) return
const clone = source.cloneNode(true)
inlineCopyStyles(source, clone)
if (source.classList.contains('attachments')) {
clone.style.display = 'block'
clone.style.width = '100%'
}
container.appendChild(clone)
})
}
if (!container.children.length && props.message.content) {
const content = document.createElement('div')
content.innerHTML = renderedContent.value
container.appendChild(content)
}
const imageJobs = Array.from(container.querySelectorAll('img')).map((image, index) => {
const attachment = imageAttachments.value[index]
const url = attachment?.url || image.getAttribute('src') || ''
const absoluteUrl = url ? new URL(url, window.location.href).href : ''
if (absoluteUrl) image.src = absoluteUrl
return { image, url: absoluteUrl }
}).filter(job => job.url)
const textParts = []
if (props.message.content) textParts.push(String(props.message.content))
if (!props.message.content && imageAttachments.value.length) {
textParts.push(...imageAttachments.value.map(att => att.name || '图片'))
}
return {
container,
text: textParts.join('\n\n'),
imageJobs
}
}
async function resolveRichCopyPayload(prepared) {
const blobs = []
await Promise.all(prepared.imageJobs.map(async ({ image, url }, index) => {
try {
const blob = await fetchImageBlob(url)
blobs[index] = blob
image.src = await blobToDataUrl(blob)
} catch {
// Keep the absolute URL so rich-text targets can still retrieve the image.
image.src = url
}
}))
return {
html: prepared.container.outerHTML,
text: prepared.text,
primaryImage: blobs.find(Boolean) || null
}
}
function legacyCopy(payload) {
const holder = document.createElement('div')
holder.contentEditable = 'true'
holder.innerHTML = payload.html
holder.style.position = 'fixed'
holder.style.left = '-10000px'
holder.style.top = '0'
holder.style.opacity = '0'
document.body.appendChild(holder)
const selection = window.getSelection()
const previousRanges = []
if (selection) {
for (let index = 0; index < selection.rangeCount; index += 1) {
previousRanges.push(selection.getRangeAt(index).cloneRange())
}
selection.removeAllRanges()
const range = document.createRange()
range.selectNodeContents(holder)
selection.addRange(range)
}
const success = document.execCommand('copy')
selection?.removeAllRanges()
previousRanges.forEach(range => selection?.addRange(range))
holder.remove()
if (!success) throw new Error('浏览器未允许复制')
}
function writeRichClipboard(prepared) {
const immediatePayload = {
html: prepared.container.outerHTML,
text: prepared.text
}
if (!navigator.clipboard?.write || typeof ClipboardItem === 'undefined') {
legacyCopy(immediatePayload)
return Promise.resolve()
}
// Start the Clipboard API call inside the click event. The payload promises may
// finish later, but the browser's transient user activation is retained.
const payloadPromise = resolveRichCopyPayload(prepared)
const representations = {
'text/html': payloadPromise.then(payload => new Blob([payload.html], { type: 'text/html' })),
'text/plain': new Blob([prepared.text], { type: 'text/plain' })
}
if (prepared.imageJobs.length) {
representations['image/png'] = payloadPromise.then(payload => {
if (!payload.primaryImage) throw new Error('图片数据读取失败')
return imageBlobToPng(payload.primaryImage)
})
}
return navigator.clipboard.write([new ClipboardItem(representations)])
}
async function copyContent() {
const text = String(props.message.content || '')
if (!text && !imageAttachments.value.length) return
let success = false
const prepared = prepareRichCopyPayload()
try {
await writeRichClipboard(prepared)
success = true
} catch {
try {
legacyCopy({ html: prepared.container.outerHTML, text: prepared.text })
success = true
} catch {
success = false
}
}
if (!success) {
notification.show({
type: 'error',
title: '复制失败',
message: '浏览器未允许访问剪贴板,请直接选中消息文字后复制。',
duration: 4500
})
return
}
copied.value = true
if (copiedTimer) clearTimeout(copiedTimer)
copiedTimer = setTimeout(() => {
copied.value = false
}, 1800)
}
</script>
@@ -118,51 +446,48 @@ function previewImage(url) {
.message {
display: flex;
gap: 10px;
width: 100%;
max-width: var(--input-max-width);
margin: 0 auto 20px;
padding: 0 8px;
}
.message.assistant {
justify-content: flex-start;
margin: 0 auto 30px;
padding: 0 10px;
}
.message.user {
flex-direction: row-reverse;
justify-content: flex-start;
}
.message-avatar {
width: 32px;
height: 32px;
border-radius: 50%;
width: 30px;
height: 30px;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
font-size: 12px;
font-weight: 600;
flex-shrink: 0;
border: 1px solid var(--border);
}
.message.user .message-avatar {
background: #5436da;
color: white;
background: #edf1f6;
color: var(--text-secondary);
}
.message.assistant .message-avatar {
background: var(--accent);
color: white;
background: var(--accent-soft);
border-color: #dbe7fa;
color: var(--accent);
}
.message-body {
display: flex;
flex-direction: column;
min-width: 0;
max-width: 78%;
padding-top: 2px;
max-width: 84%;
padding-top: 1px;
}
.message.user .message-body {
max-width: 76%;
align-items: flex-end;
}
@@ -170,39 +495,114 @@ function previewImage(url) {
align-items: flex-start;
}
.message.assistant .message-body.wide-image-message {
width: 100%;
max-width: 100%;
}
.message-content {
display: inline-block;
max-width: 100%;
color: var(--text-primary);
font-size: 15px;
line-height: 1.7;
padding: 10px 14px;
border-radius: 16px;
line-height: 1.75;
cursor: text;
user-select: text;
}
.message-actions {
display: flex;
width: 100%;
height: 0;
justify-content: flex-start;
opacity: 0;
pointer-events: none;
transform: translateY(4px);
transition: opacity 0.16s ease;
}
.image-edit-btn {
color: var(--accent);
background: var(--accent-soft);
}
.message-actions.has-image {
height: auto;
margin-top: 7px;
opacity: 1;
pointer-events: auto;
transform: none;
}
.message.user .message-actions {
justify-content: flex-end;
}
.message:hover .message-actions,
.message:focus-within .message-actions {
opacity: 1;
pointer-events: auto;
}
.message-action-btn {
min-height: 28px;
padding: 0 8px;
border-radius: 8px;
color: var(--text-muted);
display: inline-flex;
align-items: center;
gap: 5px;
font-size: 11px;
font-weight: 550;
white-space: nowrap;
transition: color 0.16s ease, background 0.16s ease, transform 0.16s ease;
}
.message-action-btn:hover,
.message-action-btn:focus-visible {
background: #fff;
color: var(--accent);
}
.message-action-btn:active {
transform: scale(0.96);
}
.message.user .message-content {
background: var(--accent);
color: #fff;
border-radius: 16px 16px 4px 16px;
padding: 11px 14px;
background: var(--accent-soft);
border: 1px solid #dbe7fa;
border-radius: 16px 16px 5px 16px;
}
.message.assistant .message-content {
background: var(--bg-tertiary);
color: var(--text-primary);
border-radius: 16px 16px 16px 4px;
padding: 3px 1px;
}
.message.streaming .message-content::after {
content: '';
display: inline-block;
width: 2px;
height: 15px;
margin-left: 3px;
border-radius: 1px;
background: var(--accent);
vertical-align: -2px;
animation: cursor-blink 0.9s step-end infinite;
}
.message-content :deep(pre) {
background: var(--bg-secondary);
background: #f6f8fb;
border-color: var(--border);
}
.message.user .message-content :deep(pre),
.message.user .message-content :deep(:not(pre) > code) {
background: rgba(0, 0, 0, 0.2);
background: rgba(255, 255, 255, 0.72);
}
.message.user .message-content :deep(a) {
color: #fff;
text-decoration: underline;
color: var(--accent);
}
.attachments {
@@ -212,54 +612,187 @@ function previewImage(url) {
margin-bottom: 8px;
}
.attachments.image-grid,
.image-loading-grid {
display: grid;
position: relative;
width: 100%;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 4px;
overflow: hidden;
border-radius: 16px;
}
.attachments.image-grid .att-image {
width: 100%;
max-width: none;
height: auto;
max-height: none;
aspect-ratio: 1 / 1;
border: 0;
border-radius: 0;
box-shadow: none;
}
.image-loading-grid i {
display: block;
aspect-ratio: 1 / 1;
background: linear-gradient(115deg, #edf2ff 8%, #f5f1ff 38%, #eaf3ff 64%, #edf2ff 92%);
background-size: 240% 100%;
animation: image-skeleton 1.8s ease-in-out infinite;
}
.generation-progress {
display: inline-flex;
position: absolute;
z-index: 1;
top: 10px;
left: 10px;
align-items: center;
gap: 4px;
padding: 5px 8px;
border: 1px solid rgba(214, 223, 241, .9);
border-radius: 8px;
background: rgba(255, 255, 255, .92);
color: #4b5565;
font-size: 12px;
font-style: normal;
font-weight: 650;
box-shadow: 0 5px 16px rgba(38, 59, 92, .08);
}
.message.user .attachments {
justify-content: flex-end;
}
.att-image {
max-width: 240px;
max-height: 240px;
border-radius: 8px;
cursor: pointer;
display: block;
width: auto;
max-width: min(100%, 460px);
max-height: 520px;
border-radius: 16px;
border: 1px solid var(--border-strong);
box-shadow: 0 12px 32px rgba(38, 59, 92, 0.1);
cursor: zoom-in;
object-fit: cover;
}
.message.user .att-image {
max-width: min(100%, 300px);
max-height: 360px;
}
.att-video {
max-width: 360px;
max-height: 240px;
border-radius: 8px;
width: min(100%, 460px);
max-height: 320px;
border-radius: 16px;
}
.att-audio {
width: 100%;
max-width: 360px;
max-width: 380px;
}
.att-document {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 8px 12px;
background: var(--bg-tertiary);
border-radius: 8px;
font-size: 13px;
gap: 7px;
max-width: 360px;
padding: 9px 11px;
background: #fff;
border: 1px solid var(--border);
border-radius: 12px;
color: var(--text-primary);
font-size: 13px;
transition: background 0.15s ease, border-color 0.15s ease;
}
.att-document:hover {
background: var(--bg-hover);
background: var(--bg-tertiary);
border-color: var(--border-strong);
}
.document-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.document-size {
color: var(--text-muted);
font-size: 11px;
white-space: nowrap;
}
@keyframes cursor-blink {
0%, 45% { opacity: 1; }
46%, 100% { opacity: 0; }
}
@keyframes image-skeleton {
0% { background-position: 100% 0; }
100% { background-position: -100% 0; }
}
@media (max-width: 768px) {
.message {
gap: 8px;
margin-bottom: 16px;
margin-bottom: 26px;
padding: 0 2px;
}
.message-body {
max-width: 85%;
.message-avatar {
width: 28px;
height: 28px;
border-radius: 9px;
}
.att-image {
max-width: 180px;
max-height: 180px;
.message-body,
.message.user .message-body {
max-width: calc(100% - 38px);
}
.message-content {
font-size: 14px;
line-height: 1.7;
}
.message.user .message-content {
padding: 10px 12px;
}
.message-actions {
opacity: 1;
pointer-events: auto;
}
.att-image,
.message.user .att-image {
max-width: 100%;
max-height: 420px;
border-radius: 14px;
}
.attachments.image-grid,
.image-loading-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
border-radius: 14px;
}
}
@media (prefers-reduced-motion: reduce) {
.message-actions,
.message-action-btn,
.message.streaming .message-content::after {
animation: none;
}
.att-document {
transition: none;
}
.image-loading-grid i {
animation: none;
}
}
</style>
+471 -48
View File
@@ -1,34 +1,74 @@
<template>
<div class="message-list" ref="listRef">
<div v-if="!visibleMessages.length && !loading && !sending && !hasStreaming" class="welcome">
<div class="welcome-icon">💬</div>
<h2>有什么可以帮您的</h2>
<p>输入消息开始对话支持 Markdown图片文件等</p>
<div class="message-list-shell">
<div
ref="listRef"
class="message-list"
@scroll.passive="handleScroll"
@wheel.passive="handleWheel"
@touchstart.passive="handleTouchStart"
@touchmove.passive="handleTouchMove"
>
<div v-if="!visibleMessages.length && !loading && !sending && !hasStreaming" class="welcome">
<div class="welcome-panel">
<div class="welcome-icon" aria-hidden="true">
<IconSparkles :size="25" :stroke-width="1.7" />
</div>
<h2>一个输入框完成对话与图片创作</h2>
<p>描述需求即可开始使用 Agent 时会自动选择语言或图片生成模型</p>
</div>
</div>
<div v-if="loading" class="loading-state" aria-label="正在加载会话">
<span></span>
<span></span>
<span></span>
</div>
<MessageItem
v-for="msg in visibleMessages"
:key="msg.id"
:message="msg"
@preview-image="openImagePreview"
/>
<MessageItem
v-if="hasStreaming"
:message="{ role: 'assistant', content: streaming, content_type: 'mixed', attachments: streamingAttachments }"
:is-streaming="true"
@preview-image="openImagePreview"
/>
<div v-if="sending && !hasStreaming" class="typing-indicator" aria-label="AI 正在回复">
<span></span><span></span><span></span>
</div>
</div>
<div v-if="loading" class="loading-state">加载中...</div>
<Transition name="scroll-button">
<button
v-if="showScrollButton"
class="scroll-bottom-btn"
type="button"
aria-label="回到最新消息"
title="回到最新消息"
@click="resumeAutoScroll"
>
<IconArrowDown :size="18" :stroke-width="2" />
<span>回到最新</span>
</button>
</Transition>
<MessageItem
v-for="msg in visibleMessages"
:key="msg.id"
:message="msg"
/>
<MessageItem
v-if="hasStreaming"
:message="{ role: 'assistant', content: streaming, content_type: 'mixed', attachments: streamingAttachments }"
:is-streaming="true"
/>
<div v-if="sending && !hasStreaming" class="typing-indicator">
<span></span><span></span><span></span>
</div>
<Teleport to="body">
<ImageWorkbench v-if="previewedImage" :image="previewedImage" @close="closeImagePreview" />
</Teleport>
</div>
</template>
<script setup>
import { ref, watch, nextTick, computed } from 'vue'
import { ref, watch, nextTick, computed, onMounted, onBeforeUnmount } from 'vue'
import IconArrowDown from '@tabler/icons-vue/dist/esm/icons/IconArrowDown.mjs'
import IconSparkles from '@tabler/icons-vue/dist/esm/icons/IconSparkles.mjs'
import MessageItem from './MessageItem.vue'
import ImageWorkbench from './ImageWorkbench.vue'
const props = defineProps({
messages: { type: Array, default: () => [] },
@@ -39,6 +79,14 @@ const props = defineProps({
})
const listRef = ref(null)
const autoScrollEnabled = ref(true)
const isAtBottom = ref(true)
const previewedImage = ref(null)
let previousBodyOverflow = ''
let previewLocksBody = false
let touchY = null
const BOTTOM_EPSILON = 2
const hasStreaming = computed(() => {
const hasText = !!(props.streaming && String(props.streaming).trim())
@@ -50,78 +98,453 @@ const visibleMessages = computed(() => {
return props.messages.filter(msg => {
const hasContent = !!(msg.content && String(msg.content).trim())
const attachments = msg.attachments || []
const hasAttachments = Array.isArray(attachments) && attachments.length > 0
const hasAttachments = Array.isArray(attachments) ? attachments.length > 0 : false
return hasContent || hasAttachments
})
})
const showScrollButton = computed(() => {
return !isAtBottom.value && (visibleMessages.value.length > 0 || hasStreaming.value)
})
function distanceFromBottom() {
const el = listRef.value
if (!el) return 0
return Math.max(0, el.scrollHeight - el.clientHeight - el.scrollTop)
}
function handleScroll() {
const atBottom = distanceFromBottom() <= BOTTOM_EPSILON
isAtBottom.value = atBottom
autoScrollEnabled.value = atBottom
}
function pauseAutoScroll() {
autoScrollEnabled.value = false
isAtBottom.value = false
}
function handleWheel(event) {
if (event.deltaY < 0) pauseAutoScroll()
}
function handleTouchStart(event) {
touchY = event.touches?.[0]?.clientY ?? null
}
function handleTouchMove(event) {
const currentY = event.touches?.[0]?.clientY
if (currentY == null || touchY == null) return
if (currentY > touchY + 2) pauseAutoScroll()
touchY = currentY
}
function scrollToBottom() {
const el = listRef.value
if (!el) return
el.scrollTop = el.scrollHeight
isAtBottom.value = true
}
function resumeAutoScroll() {
autoScrollEnabled.value = true
scrollToBottom()
}
function openImagePreview(image) {
if (!image?.url) return
previewedImage.value = image
}
function closeImagePreview() {
previewedImage.value = null
}
function handlePreviewKeydown(event) {
if (event.key === 'Escape' && previewedImage.value) {
closeImagePreview()
}
}
watch(previewedImage, (image, previousImage) => {
if (image && !previousImage) {
previousBodyOverflow = document.body.style.overflow
document.body.style.overflow = 'hidden'
previewLocksBody = true
} else if (!image && previousImage && previewLocksBody) {
document.body.style.overflow = previousBodyOverflow
previewLocksBody = false
}
})
onMounted(() => {
window.addEventListener('keydown', handlePreviewKeydown)
})
onBeforeUnmount(() => {
window.removeEventListener('keydown', handlePreviewKeydown)
if (previewLocksBody) {
document.body.style.overflow = previousBodyOverflow
previewLocksBody = false
}
})
watch(
() => [props.messages.length, props.streaming, props.streamingAttachments?.length],
() => {
const last = visibleMessages.value[visibleMessages.value.length - 1]
return [visibleMessages.value.length, last?.id, last?.role]
},
async () => {
const last = visibleMessages.value[visibleMessages.value.length - 1]
if (last?.role === 'user') {
autoScrollEnabled.value = true
}
await nextTick()
if (autoScrollEnabled.value) scrollToBottom()
}
)
watch(
() => [props.streaming, props.streamingAttachments?.length, props.sending],
async () => {
await nextTick()
if (listRef.value) {
listRef.value.scrollTop = listRef.value.scrollHeight
}
if (autoScrollEnabled.value) scrollToBottom()
}
)
watch(
() => props.loading,
async (loading, previousLoading) => {
if (loading || !previousLoading) return
autoScrollEnabled.value = true
await nextTick()
scrollToBottom()
}
)
</script>
<style scoped>
.message-list {
.message-list-shell {
position: relative;
flex: 1;
min-height: 0;
}
.message-list {
width: 100%;
height: 100%;
overflow-y: auto;
padding: 24px 16px;
overscroll-behavior: contain;
padding: 24px 24px 18px;
}
.scroll-bottom-btn {
position: absolute;
left: 50%;
bottom: 12px;
z-index: 12;
min-height: 38px;
padding: 0 14px;
border: 1px solid var(--border-strong);
border-radius: 999px;
background: rgba(255, 255, 255, 0.96);
box-shadow: 0 10px 30px rgba(38, 59, 92, 0.14);
color: var(--text-secondary);
display: inline-flex;
align-items: center;
gap: 7px;
font-size: 12px;
font-weight: 600;
transform: translateX(-50%);
backdrop-filter: blur(10px);
transition: color 0.16s ease, border-color 0.16s ease, box-shadow 0.16s ease, transform 0.16s ease;
}
.scroll-bottom-btn:hover {
color: var(--accent);
border-color: rgba(45, 102, 218, 0.32);
box-shadow: 0 12px 34px rgba(38, 59, 92, 0.18);
transform: translateX(-50%) translateY(-1px);
}
.scroll-bottom-btn:active {
transform: translateX(-50%) scale(0.97);
}
.scroll-button-enter-active,
.scroll-button-leave-active {
transition: opacity 0.18s ease, transform 0.18s ease;
}
.scroll-button-enter-from,
.scroll-button-leave-to {
opacity: 0;
transform: translateX(-50%) translateY(7px);
}
.image-preview-overlay {
position: fixed;
inset: 0;
z-index: 1000;
display: grid;
grid-template-rows: minmax(0, 1fr) auto;
padding: 58px 28px 22px;
background: rgba(12, 19, 31, 0.88);
backdrop-filter: blur(14px);
}
.image-preview-stage {
display: flex;
min-width: 0;
min-height: 0;
align-items: center;
justify-content: center;
}
.image-preview-full {
display: block;
width: auto;
height: auto;
max-width: 94vw;
max-height: calc(100vh - 112px);
border-radius: 14px;
box-shadow: 0 28px 80px rgba(0, 0, 0, 0.38);
object-fit: contain;
user-select: none;
}
.image-preview-close {
position: fixed;
top: 18px;
right: 20px;
z-index: 1;
width: 40px;
height: 40px;
border: 1px solid rgba(255, 255, 255, 0.24);
border-radius: 12px;
background: rgba(255, 255, 255, 0.12);
color: #fff;
display: flex;
align-items: center;
justify-content: center;
backdrop-filter: blur(10px);
transition: background 0.16s ease, transform 0.16s ease;
}
.image-preview-close:hover,
.image-preview-close:focus-visible {
background: rgba(255, 255, 255, 0.22);
}
.image-preview-close:active {
transform: scale(0.95);
}
.image-preview-caption {
max-width: min(80vw, 720px);
margin: 14px auto 0;
overflow: hidden;
color: rgba(255, 255, 255, 0.78);
font-size: 12px;
line-height: 1.4;
text-align: center;
text-overflow: ellipsis;
white-space: nowrap;
}
.image-preview-enter-active,
.image-preview-leave-active {
transition: opacity 0.2s ease;
}
.image-preview-enter-active .image-preview-full,
.image-preview-leave-active .image-preview-full {
transition: transform 0.22s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.2s ease;
}
.image-preview-enter-from,
.image-preview-leave-to {
opacity: 0;
}
.image-preview-enter-from .image-preview-full,
.image-preview-leave-to .image-preview-full {
opacity: 0;
transform: scale(0.96);
}
.welcome {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
min-height: 100%;
}
.welcome-panel {
width: min(100%, 620px);
padding: 24px 18px 30px;
text-align: center;
color: var(--text-secondary);
animation: welcome-in 0.45s cubic-bezier(0.16, 1, 0.3, 1) both;
}
.welcome-icon {
font-size: 64px;
margin-bottom: 16px;
width: 52px;
height: 52px;
margin: 0 auto 18px;
border-radius: 16px;
background: #fff;
border: 1px solid var(--border-strong);
color: var(--accent);
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 10px 28px rgba(38, 59, 92, 0.08);
}
.welcome h2 {
font-size: 24px;
margin-bottom: 10px;
color: var(--text-primary);
margin-bottom: 8px;
font-size: clamp(23px, 2.4vw, 28px);
font-weight: 680;
letter-spacing: -0.035em;
line-height: 1.28;
}
.welcome p {
max-width: 460px;
margin: 0 auto;
color: var(--text-secondary);
font-size: 14px;
line-height: 1.65;
}
.loading-state {
text-align: center;
padding: 24px;
color: var(--text-muted);
width: min(100%, 680px);
margin: 28px auto;
padding: 18px 0;
}
.loading-state span {
display: block;
height: 12px;
margin-bottom: 10px;
border-radius: 6px;
background: #e8edf3;
animation: skeleton-pulse 1.2s ease-in-out infinite;
}
.loading-state span:nth-child(1) {
width: 68%;
}
.loading-state span:nth-child(2) {
width: 88%;
}
.loading-state span:nth-child(3) {
width: 52%;
}
.typing-indicator {
display: flex;
gap: 4px;
padding: 16px 24px;
max-width: var(--input-max-width);
margin: 0 auto;
padding: 12px 40px;
}
.typing-indicator span {
width: 8px;
height: 8px;
background: var(--text-muted);
width: 7px;
height: 7px;
background: #aab5c4;
border-radius: 50%;
animation: bounce 1.4s infinite ease-in-out both;
animation: bounce 1.2s infinite ease-in-out both;
}
.typing-indicator span:nth-child(1) {
animation-delay: -0.24s;
}
.typing-indicator span:nth-child(2) {
animation-delay: -0.12s;
}
@keyframes welcome-in {
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes skeleton-pulse {
0%, 100% { opacity: 0.55; }
50% { opacity: 1; }
}
.typing-indicator span:nth-child(1) { animation-delay: -0.32s; }
.typing-indicator span:nth-child(2) { animation-delay: -0.16s; }
@keyframes bounce {
0%, 80%, 100% { transform: scale(0); }
40% { transform: scale(1); }
0%, 80%, 100% { transform: scale(0.65); opacity: 0.45; }
40% { transform: scale(1); opacity: 1; }
}
@media (max-width: 768px) {
.message-list {
padding: 14px 12px 10px;
}
.scroll-bottom-btn {
bottom: 8px;
min-height: 36px;
padding: 0 12px;
}
.welcome-panel {
padding: 18px 10px 24px;
}
.welcome-icon {
width: 48px;
height: 48px;
margin-bottom: 16px;
border-radius: 15px;
}
.welcome h2 {
max-width: 330px;
margin-right: auto;
margin-left: auto;
font-size: 23px;
line-height: 1.3;
}
.welcome p {
max-width: 310px;
font-size: 13px;
}
.image-preview-overlay {
padding: 54px 12px 16px;
}
.image-preview-full {
max-width: calc(100vw - 24px);
max-height: calc(100vh - 100px);
border-radius: 10px;
}
.image-preview-close {
top: 12px;
right: 12px;
}
}
@media (prefers-reduced-motion: reduce) {
.scroll-bottom-btn,
.image-preview-overlay,
.image-preview-full,
.image-preview-close,
.welcome-panel,
.loading-state span,
.typing-indicator span {
animation: none;
}
}
</style>
@@ -0,0 +1,292 @@
<template>
<Teleport to="body">
<section class="notification-region" aria-label="系统通知" aria-live="assertive">
<TransitionGroup name="notification">
<article
v-for="item in notification.notifications"
:key="item.id"
class="notification-card"
:class="`notification-${item.type}`"
role="alert"
>
<div class="notification-icon" aria-hidden="true">
<IconAlertTriangle :size="20" :stroke-width="1.8" />
</div>
<div class="notification-content">
<div class="notification-heading">
<strong>{{ item.title }}</strong>
<button
class="notification-close"
type="button"
aria-label="关闭提示"
@click="notification.dismiss(item.id)"
>
<IconX :size="17" :stroke-width="1.8" />
</button>
</div>
<p>{{ item.message }}</p>
<details v-if="item.detail" class="notification-detail">
<summary>
<span>查看技术详情</span>
<IconChevronDown class="detail-chevron" :size="16" :stroke-width="1.8" />
</summary>
<div class="detail-body">
<pre>{{ item.detail }}</pre>
<button class="copy-detail" type="button" @click="copyDetail(item)">
<IconCheck v-if="copiedId === item.id" :size="15" :stroke-width="1.8" />
<IconCopy v-else :size="15" :stroke-width="1.8" />
{{ copiedId === item.id ? '已复制' : '复制详情' }}
</button>
</div>
</details>
</div>
</article>
</TransitionGroup>
</section>
</Teleport>
</template>
<script setup>
import { ref } from 'vue'
import IconAlertTriangle from '@tabler/icons-vue/dist/esm/icons/IconAlertTriangle.mjs'
import IconCheck from '@tabler/icons-vue/dist/esm/icons/IconCheck.mjs'
import IconChevronDown from '@tabler/icons-vue/dist/esm/icons/IconChevronDown.mjs'
import IconCopy from '@tabler/icons-vue/dist/esm/icons/IconCopy.mjs'
import IconX from '@tabler/icons-vue/dist/esm/icons/IconX.mjs'
import { useNotificationStore } from '@/stores/notification'
const notification = useNotificationStore()
const copiedId = ref(null)
let copiedTimer = null
async function copyDetail(item) {
try {
await navigator.clipboard.writeText(item.detail)
copiedId.value = item.id
if (copiedTimer) clearTimeout(copiedTimer)
copiedTimer = setTimeout(() => {
copiedId.value = null
}, 1800)
} catch {
copiedId.value = null
}
}
</script>
<style scoped>
.notification-region {
position: fixed;
top: 16px;
right: 16px;
z-index: 120;
display: flex;
width: min(420px, calc(100vw - 32px));
flex-direction: column;
gap: 10px;
pointer-events: none;
}
.notification-card {
position: relative;
display: grid;
grid-template-columns: 38px minmax(0, 1fr);
gap: 12px;
overflow: hidden;
padding: 14px;
background: rgba(255, 255, 255, 0.98);
border: 1px solid var(--border-strong);
border-radius: 16px;
box-shadow: 0 18px 48px rgba(38, 59, 92, 0.16);
pointer-events: auto;
}
.notification-card::before {
content: '';
position: absolute;
inset: 0 auto 0 0;
width: 3px;
background: var(--danger);
}
.notification-icon {
width: 38px;
height: 38px;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
background: #fff0f0;
color: var(--danger);
}
.notification-content {
min-width: 0;
}
.notification-heading {
display: flex;
min-height: 28px;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
}
.notification-heading strong {
padding-top: 2px;
color: var(--text-primary);
font-size: 15px;
font-weight: 650;
line-height: 1.4;
}
.notification-close {
width: 28px;
height: 28px;
margin: -3px -4px 0 0;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
color: var(--text-muted);
flex-shrink: 0;
transition: background 0.16s ease, color 0.16s ease, transform 0.16s ease;
}
.notification-close:hover {
background: var(--bg-soft);
color: var(--text-primary);
}
.notification-close:active,
.copy-detail:active {
transform: scale(0.96);
}
.notification-content > p {
max-width: 36em;
color: var(--text-secondary);
font-size: 13px;
line-height: 1.65;
text-wrap: pretty;
}
.notification-detail {
margin-top: 10px;
border-top: 1px solid var(--border);
}
.notification-detail summary {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 10px 0 1px;
color: var(--text-secondary);
font-size: 12px;
font-weight: 550;
cursor: pointer;
list-style: none;
user-select: none;
}
.notification-detail summary::-webkit-details-marker {
display: none;
}
.detail-chevron {
transition: transform 0.18s ease;
}
.notification-detail[open] .detail-chevron {
transform: rotate(180deg);
}
.detail-body {
margin-top: 8px;
padding: 10px;
background: #f6f8fb;
border: 1px solid var(--border);
border-radius: 10px;
}
.detail-body pre {
max-height: 190px;
overflow: auto;
color: #354258;
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
font-size: 11px;
line-height: 1.55;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.copy-detail {
display: inline-flex;
align-items: center;
gap: 5px;
min-height: 30px;
margin-top: 9px;
padding: 0 9px;
background: #fff;
border: 1px solid var(--border-strong);
border-radius: 8px;
color: var(--text-secondary);
font-size: 11px;
transition: background 0.16s ease, color 0.16s ease, transform 0.16s ease;
}
.copy-detail:hover {
background: var(--bg-soft);
color: var(--text-primary);
}
.notification-enter-active,
.notification-leave-active {
transition: opacity 0.22s ease, transform 0.22s cubic-bezier(0.16, 1, 0.3, 1);
}
.notification-enter-from,
.notification-leave-to {
opacity: 0;
transform: translateY(-8px) scale(0.98);
}
@media (max-width: 768px) {
.notification-region {
top: calc(10px + env(safe-area-inset-top));
right: 10px;
left: 10px;
width: auto;
}
.notification-card {
grid-template-columns: 34px minmax(0, 1fr);
gap: 10px;
padding: 12px;
border-radius: 14px;
}
.notification-icon {
width: 34px;
height: 34px;
border-radius: 10px;
}
.detail-body pre {
max-height: min(220px, 36dvh);
}
}
@media (prefers-reduced-motion: reduce) {
.notification-enter-active,
.notification-leave-active,
.notification-close,
.copy-detail,
.detail-chevron {
transition: none;
}
}
</style>
+1 -1
View File
@@ -39,7 +39,7 @@ router.beforeEach(async (to, from, next) => {
return
}
if (to.meta.guest && auth.isLoggedIn) {
if (to.meta.guest && auth.isLoggedIn && !auth.isGuest) {
next({ name: 'Chat' })
return
}
+31 -12
View File
@@ -1,6 +1,7 @@
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/api'
import { getOrCreateGuestKey } from '@/utils/guestSession'
export const useAuthStore = defineStore('auth', () => {
const token = ref(localStorage.getItem('token') || '')
@@ -8,32 +9,49 @@ export const useAuthStore = defineStore('auth', () => {
const initialized = ref(false)
const isLoggedIn = computed(() => !!token.value && !!user.value)
const isGuest = computed(() => !!user.value?.is_guest)
function setSession(data, type) {
token.value = data.token
user.value = data.user
localStorage.setItem('token', token.value)
localStorage.setItem('auth_type', type)
}
async function enterGuestMode() {
const res = await api.post('/auth/guest', { guest_key: getOrCreateGuestKey() })
setSession(res.data.data, 'guest')
return res.data
}
async function init() {
if (token.value) {
try {
try {
if (token.value) {
const res = await api.get('/auth/me')
user.value = res.data.data
} catch {
logout()
localStorage.setItem('auth_type', user.value?.is_guest ? 'guest' : 'account')
}
if (!user.value) {
await enterGuestMode()
}
} catch {
logout()
await enterGuestMode()
} finally {
initialized.value = true
}
initialized.value = true
}
async function login(account, password) {
const res = await api.post('/auth/login', { account, password })
token.value = res.data.data.token
user.value = res.data.data.user
localStorage.setItem('token', token.value)
setSession(res.data.data, 'account')
return res.data
}
async function register(username, email, password) {
const res = await api.post('/auth/register', { username, email, password })
token.value = res.data.data.token
user.value = res.data.data.user
localStorage.setItem('token', token.value)
setSession(res.data.data, 'account')
return res.data
}
@@ -41,7 +59,8 @@ export const useAuthStore = defineStore('auth', () => {
token.value = ''
user.value = null
localStorage.removeItem('token')
localStorage.removeItem('auth_type')
}
return { token, user, initialized, isLoggedIn, init, login, register, logout }
return { token, user, initialized, isLoggedIn, isGuest, init, enterGuestMode, login, register, logout }
})
+92 -25
View File
@@ -55,6 +55,7 @@ export const useChatStore = defineStore('chat', () => {
const sidebarOpen = ref(false)
/** 侧边栏当前选中的模型,发送/新建会话都会使用它 */
const selectedModelId = ref(null)
const selectedAgentId = ref(localStorage.getItem('selected_agent_id') || null)
let pendingPollTimer = null
let pendingPollInFlight = false
@@ -183,36 +184,53 @@ export const useChatStore = defineStore('chat', () => {
}
}
async function sendMessage(content, attachments = []) {
if (!currentId.value) {
await createConversation(selectedModelId.value)
} else if (selectedModelId.value != null) {
// 发送前确保当前会话已绑定侧边栏所选模型
const conv = conversations.value.find(c => c.id === currentId.value)
if (conv && Number(conv.model_id) !== Number(selectedModelId.value)) {
await setSelectedModel(selectedModelId.value)
}
function setSelectedAgent(agentId) {
selectedAgentId.value = agentId || null
if (selectedAgentId.value) {
localStorage.setItem('selected_agent_id', selectedAgentId.value)
} else {
localStorage.removeItem('selected_agent_id')
}
}
async function sendMessage(content, attachments = [], agentId = selectedAgentId.value, options = {}) {
if (sending.value) return
const userMsg = {
id: Date.now(),
role: 'user',
content,
attachments,
created_at: new Date().toISOString()
}
messages.value.push(userMsg)
sending.value = true
streamingContent.value = ''
streamingAttachments.value = []
let userMsg = null
try {
await streamChat(content, attachments)
if (!currentId.value) {
await createConversation(selectedModelId.value)
} else if (selectedModelId.value != null) {
// 发送前确保当前会话已绑定侧边栏所选模型
const conv = conversations.value.find(c => c.id === currentId.value)
if (conv && Number(conv.model_id) !== Number(selectedModelId.value)) {
await setSelectedModel(selectedModelId.value)
}
}
userMsg = {
id: Date.now(),
role: 'user',
content,
attachments,
created_at: new Date().toISOString()
}
messages.value.push(userMsg)
await streamChat(content, attachments, agentId, options)
await loadMessages()
} catch (e) {
// 连接断开/代理超时:任务可能已落库为 pending,先同步再决定是否抛错
messages.value = messages.value.filter(m => m.id !== userMsg.id)
const cancelled = e?.name === 'AbortError' || options.signal?.aborted
if (userMsg) {
messages.value = messages.value.filter(m => m.id !== userMsg.id)
}
await loadMessages().catch(() => {})
if (cancelled) throw e
if (hasPendingJobs(messages.value)) {
startPendingJobPolling()
return
@@ -225,7 +243,7 @@ export const useChatStore = defineStore('chat', () => {
}
}
async function streamChat(content, attachments) {
async function streamChat(content, attachments, agentId = null, options = {}) {
const token = localStorage.getItem('token')
const response = await fetch('/api/chat/completions', {
method: 'POST',
@@ -233,10 +251,13 @@ export const useChatStore = defineStore('chat', () => {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
signal: options.signal,
body: JSON.stringify({
conversation_id: currentId.value,
content,
attachments,
agent_id: agentId || null,
image_tool: options.imageTool || null,
stream: true
})
})
@@ -257,8 +278,47 @@ export const useChatStore = defineStore('chat', () => {
const decoder = new TextDecoder()
let buffer = ''
let fullContent = ''
let receivedContent = ''
let gotAttachments = false
let pendingDone = false
let agentRenderVersion = 0
let agentRenderQueue = Promise.resolve()
const isAgentStream = !!agentId
const appendVisibleContent = (content) => {
if (!content) return
receivedContent += content
if (!isAgentStream) {
fullContent += content
streamingContent.value = fullContent
return
}
const version = agentRenderVersion
const characters = Array.from(content)
const frameCount = Math.min(10, Math.max(2, Math.ceil(characters.length / 8)))
const frameSize = Math.ceil(characters.length / frameCount)
agentRenderQueue = agentRenderQueue.then(async () => {
for (let index = 0; index < characters.length; index += frameSize) {
if (version !== agentRenderVersion) return
fullContent += characters.slice(index, index + frameSize).join('')
streamingContent.value = fullContent
if (index + frameSize < characters.length) {
await new Promise(resolve => setTimeout(resolve, 14))
}
}
})
}
const replaceVisibleContent = (content) => {
agentRenderVersion++
agentRenderQueue = Promise.resolve()
receivedContent = content
fullContent = content
streamingContent.value = content
}
while (true) {
const { done, value } = await reader.read()
@@ -274,6 +334,7 @@ export const useChatStore = defineStore('chat', () => {
const { event, data } = parseSseBlock(block)
if (event === 'error') {
agentRenderVersion++
throw new Error(data?.message || 'AI 请求失败')
}
@@ -287,8 +348,11 @@ export const useChatStore = defineStore('chat', () => {
}
if (event === 'message' && data?.content) {
fullContent += data.content
streamingContent.value = fullContent
appendVisibleContent(data.content)
}
if (event === 'replace' && typeof data?.content === 'string') {
replaceVisibleContent(data.content)
}
if (event === 'done') {
@@ -298,9 +362,8 @@ export const useChatStore = defineStore('chat', () => {
streamingContent.value = data.content
}
}
if (data?.content && !fullContent) {
fullContent = data.content
streamingContent.value = fullContent
if (data?.content && !receivedContent) {
appendVisibleContent(data.content)
}
if (Array.isArray(data?.attachments) && data.attachments.length) {
streamingAttachments.value = data.attachments
@@ -310,6 +373,8 @@ export const useChatStore = defineStore('chat', () => {
}
}
await agentRenderQueue
if (pendingDone) {
await loadMessages().catch(() => {})
startPendingJobPolling()
@@ -350,10 +415,12 @@ export const useChatStore = defineStore('chat', () => {
streamingAttachments,
sidebarOpen,
selectedModelId,
selectedAgentId,
fetchConversations,
createConversation,
selectConversation,
setSelectedModel,
setSelectedAgent,
deleteConversation,
sendMessage,
loadMessages,
+45
View File
@@ -0,0 +1,45 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { presentError } from '@/utils/errorPresentation'
let nextId = 1
export const useNotificationStore = defineStore('notification', () => {
const notifications = ref([])
const timers = new Map()
function dismiss(id) {
const timer = timers.get(id)
if (timer) clearTimeout(timer)
timers.delete(id)
notifications.value = notifications.value.filter(item => item.id !== id)
}
function show(payload) {
const id = nextId++
const item = {
id,
type: payload.type || 'error',
title: payload.title || '请求失败',
message: payload.message || '请求未能完成,请稍后重试。',
detail: payload.detail || ''
}
notifications.value = [...notifications.value.slice(-2), item]
if (payload.duration > 0) {
timers.set(id, setTimeout(() => dismiss(id), payload.duration))
}
return id
}
function error(errorValue, options = {}) {
return show({
type: 'error',
...presentError(errorValue, options),
duration: options.duration ?? 0
})
}
return { notifications, show, error, dismiss }
})
+7 -1
View File
@@ -18,6 +18,7 @@ export const useSettingsStore = defineStore('settings', () => {
const siteName = ref('AI Chat')
const allowRegister = ref(true)
const models = ref([])
const agents = ref([])
const loaded = ref(false)
async function loadPublic() {
@@ -34,5 +35,10 @@ export const useSettingsStore = defineStore('settings', () => {
models.value = res.data.data
}
return { features, siteName, allowRegister, models, loaded, loadPublic, loadModels }
async function loadAgents() {
const res = await api.get('/agents')
agents.value = res.data.data || []
}
return { features, siteName, allowRegister, models, agents, loaded, loadPublic, loadModels, loadAgents }
})
+126
View File
@@ -0,0 +1,126 @@
function toText(value) {
if (typeof value === 'string') return value.trim()
if (value == null) return ''
try {
return JSON.stringify(value)
} catch {
return String(value)
}
}
function extractRawError(error) {
if (typeof error === 'string') return error.trim()
return toText(
error?.response?.data?.message
|| error?.response?.data?.error
|| error?.detail
|| error?.message
|| error
) || '请求未能完成'
}
function parseEmbeddedJson(raw) {
const start = raw.search(/[\[{]/)
if (start < 0) return { data: null, prefix: '', formatted: '' }
const candidate = raw.slice(start).trim()
try {
const data = JSON.parse(candidate)
const prefix = raw.slice(0, start).trim().replace(/[:;]+$/, '')
const formattedJson = JSON.stringify(data, null, 2)
return {
data,
prefix,
formatted: prefix ? `${prefix}\n\n${formattedJson}` : formattedJson
}
} catch {
return { data: null, prefix: '', formatted: '' }
}
}
function findDeviceValidation(value) {
if (Array.isArray(value)) {
for (const item of value) {
const match = findDeviceValidation(item)
if (match) return match
}
return null
}
if (!value || typeof value !== 'object') return null
const info = value.extra_info
if (info?.input_name === 'device') {
const options = Array.isArray(info.input_config?.[0]) ? info.input_config[0] : []
return {
received: toText(info.received_value),
options: options.map(toText).filter(Boolean)
}
}
for (const child of Object.values(value)) {
const match = findDeviceValidation(child)
if (match) return match
}
return null
}
function humanizeComfyError(raw, parsed) {
const device = findDeviceValidation(parsed)
if (device?.received) {
const allowed = device.options.length ? `,当前可用选项为 ${device.options.join('、')}` : ''
return `工作流请求使用设备 ${device.received}${allowed}。请修改 ComfyUI 的 device 节点配置后重试。`
}
if (/value_not_in_list|Prompt outputs failed validation/i.test(raw)) {
return '工作流参数没有通过 ComfyUI 校验,请检查对应节点、模型和设备配置后重试。'
}
if (/拒绝任务|execution error|执行失败/i.test(raw)) {
return 'ComfyUI 拒绝了本次生成任务,请检查工作流和节点配置后重试。'
}
return '图片生成服务暂时无法完成任务,请检查 ComfyUI 配置后重试。'
}
function defaultTitle(raw, status) {
if (/ComfyUI|Prompt outputs failed|value_not_in_list/i.test(raw)) return '图片生成失败'
if (status === 401) return '登录状态已失效'
if (status === 403) return '没有操作权限'
if (/network|Failed to fetch|ERR_NETWORK|连接失败/i.test(raw)) return '连接失败'
if (/timeout|超时/i.test(raw)) return '请求超时'
return '请求失败'
}
function defaultMessage(raw, status, parsed) {
if (/ComfyUI|Prompt outputs failed|value_not_in_list/i.test(raw)) {
return humanizeComfyError(raw, parsed)
}
if (status === 401) return '登录信息已过期,请重新登录。'
if (status === 403) return '当前账户没有执行此操作的权限。'
if (/network|Failed to fetch|ERR_NETWORK|连接失败/i.test(raw)) {
return '暂时无法连接服务,请检查网络或服务状态后重试。'
}
if (/timeout|超时/i.test(raw)) return '服务响应时间过长,请稍后重试。'
const beforeJson = raw.split(/[\[{]/, 1)[0].trim().replace(/[:;]+$/, '')
if (beforeJson && beforeJson.length <= 120) return beforeJson
if (raw.length <= 120) return raw
return '服务返回了异常信息,请稍后重试或查看技术详情。'
}
export function presentError(error, options = {}) {
const raw = extractRawError(error)
const status = error?.status || error?.response?.status || null
const embedded = parseEmbeddedJson(raw)
const isTechnical = raw.length > 140
|| !!embedded.formatted
|| /value_not_in_list|Prompt outputs failed|stack|traceback/i.test(raw)
return {
title: options.title || defaultTitle(raw, status),
message: options.message || defaultMessage(raw, status, embedded.data),
detail: options.detail ?? (isTechnical ? (embedded.formatted || raw) : ''),
status
}
}
+17
View File
@@ -0,0 +1,17 @@
const GUEST_KEY_STORAGE = 'guest_key'
export function getGuestKey() {
const key = localStorage.getItem(GUEST_KEY_STORAGE) || ''
return /^[a-f0-9]{64}$/.test(key) ? key : ''
}
export function getOrCreateGuestKey() {
const existing = getGuestKey()
if (existing) return existing
const bytes = new Uint8Array(32)
crypto.getRandomValues(bytes)
const key = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')
localStorage.setItem(GUEST_KEY_STORAGE, key)
return key
}
+112 -25
View File
@@ -10,20 +10,35 @@
<main class="chat-main">
<header class="chat-header">
<button class="menu-btn" @click="chat.toggleSidebar">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M3 12h18M3 6h18M3 18h18"/>
</svg>
<button class="menu-btn" type="button" aria-label="打开会话列表" @click="chat.toggleSidebar">
<IconMenu2 :size="21" :stroke-width="1.8" />
</button>
<h2 class="chat-title">{{ currentTitle }}</h2>
<div class="chat-heading">
<span class="chat-kicker">AI 创作空间</span>
<h2 class="chat-title">{{ currentTitle }}</h2>
</div>
<div class="header-actions">
<a
v-if="auth.user?.role === 'admin'"
:href="adminUrl"
target="_blank"
rel="noopener"
class="btn btn-ghost btn-sm admin-link"
>管理后台</a>
<button class="btn btn-ghost btn-sm" @click="handleLogout">退出</button>
aria-label="打开管理后台"
>
<IconSettings :size="17" :stroke-width="1.8" />
<span class="action-label">后台</span>
</a>
<button
class="btn btn-ghost btn-sm"
type="button"
:aria-label="auth.isGuest ? '登录账户' : '退出登录'"
@click="handleAccountAction"
>
<IconLogin v-if="auth.isGuest" :size="17" :stroke-width="1.8" />
<IconLogout v-else :size="17" :stroke-width="1.8" />
<span class="action-label">{{ auth.isGuest ? '登录' : '退出' }}</span>
</button>
</div>
</header>
@@ -45,14 +60,20 @@ import { computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useChatStore } from '@/stores/chat'
import { useNotificationStore } from '@/stores/notification'
import { useSettingsStore } from '@/stores/settings'
import ChatSidebar from '@/components/ChatSidebar.vue'
import MessageList from '@/components/MessageList.vue'
import ChatInput from '@/components/ChatInput.vue'
import IconLogout from '@tabler/icons-vue/dist/esm/icons/IconLogout.mjs'
import IconLogin from '@tabler/icons-vue/dist/esm/icons/IconLogin.mjs'
import IconMenu2 from '@tabler/icons-vue/dist/esm/icons/IconMenu2.mjs'
import IconSettings from '@tabler/icons-vue/dist/esm/icons/IconSettings.mjs'
const router = useRouter()
const auth = useAuthStore()
const chat = useChatStore()
const notification = useNotificationStore()
const settings = useSettingsStore()
const currentTitle = computed(() => {
@@ -63,20 +84,29 @@ const currentTitle = computed(() => {
const adminUrl = import.meta.env.VITE_ADMIN_URL || `${window.location.protocol}//${window.location.hostname}:5174`
onMounted(async () => {
await settings.loadPublic()
await settings.loadModels()
await chat.fetchConversations()
try {
await settings.loadPublic()
await Promise.all([settings.loadModels(), settings.loadAgents()])
await chat.fetchConversations()
} catch (err) {
notification.error(err, { title: '页面加载失败' })
}
})
async function handleSend({ content, attachments }) {
async function handleSend({ content, attachments, agentId }) {
try {
await chat.sendMessage(content, attachments)
await chat.sendMessage(content, attachments, agentId)
} catch (e) {
alert(e.message)
notification.error(e)
}
}
function handleLogout() {
function handleAccountAction() {
if (auth.isGuest) {
router.push('/login')
return
}
auth.logout()
router.push('/login')
}
@@ -86,7 +116,9 @@ function handleLogout() {
.chat-layout {
display: flex;
height: 100%;
min-height: 100dvh;
overflow: hidden;
background: linear-gradient(180deg, #f8faff 0%, var(--bg-primary) 100%);
}
.chat-main {
@@ -94,33 +126,58 @@ function handleLogout() {
display: flex;
flex-direction: column;
min-width: 0;
background: var(--bg-primary);
background: transparent;
}
.chat-header {
display: flex;
align-items: center;
gap: 12px;
gap: 10px;
height: var(--header-height);
padding: 0 16px;
border-bottom: 1px solid var(--border);
padding: 0 22px;
border-bottom: 1px solid rgba(225, 231, 239, 0.92);
background: rgba(255, 255, 255, 0.86);
backdrop-filter: blur(14px);
flex-shrink: 0;
}
.menu-btn {
display: none;
padding: 8px;
border-radius: 8px;
width: 36px;
height: 36px;
align-items: center;
justify-content: center;
border-radius: 50%;
color: var(--text-secondary);
transition: background 0.16s ease, color 0.16s ease, transform 0.16s ease;
}
.menu-btn:hover {
background: var(--bg-hover);
background: var(--bg-soft);
color: var(--text-primary);
}
.menu-btn:active {
transform: scale(0.96);
}
.chat-heading {
flex: 1;
min-width: 0;
}
.chat-kicker {
display: inline-block;
margin-bottom: 1px;
font-size: 10px;
letter-spacing: 0.04em;
color: var(--text-muted);
}
.chat-title {
flex: 1;
font-size: 16px;
font-weight: 500;
font-weight: 650;
line-height: 1.25;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
@@ -128,17 +185,47 @@ function handleLogout() {
.header-actions {
display: flex;
gap: 4px;
gap: 6px;
}
.btn-sm {
padding: 6px 12px;
min-height: 36px;
padding: 7px 12px;
font-size: 13px;
}
@media (max-width: 768px) {
.chat-header {
padding: 0 10px 0 8px;
}
.menu-btn {
display: flex;
}
.chat-kicker {
display: none;
}
.chat-title {
font-size: 17px;
}
.btn-sm {
width: 36px;
min-height: 36px;
padding: 0;
border-radius: 50%;
}
.action-label {
display: none;
}
}
@media (prefers-reduced-motion: reduce) {
.menu-btn {
transition: none;
}
}
</style>
+6
View File
@@ -8,6 +8,12 @@
"build:member": "npm --prefix frontend run build",
"build:admin": "npm --prefix frontend-admin run build",
"deploy:static": "node scripts/deploy-static.js",
"test:agent:100": "php backend/tests/agent_100_round_regression.php",
"test:llm:100": "php backend/tests/llm_100_round_regression.php",
"test:image:regression": "php backend/tests/comfy_image_edit_regression.php",
"test:image:integration": "php backend/tests/comfy_image_edit_integration.php",
"test:stability:1000": "powershell -ExecutionPolicy Bypass -File scripts/run-stability-suite.ps1",
"test:conversation:3000": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/run-conversation-adversarial.ps1 -Rounds 3000",
"preview:member": "npm --prefix frontend run preview",
"preview:admin": "npm --prefix frontend-admin run preview"
}
+56
View File
@@ -0,0 +1,56 @@
param(
[ValidateScript({ $_ -ge 100 -and $_ % 100 -eq 0 })]
[int]$Rounds = 3000
)
$ErrorActionPreference = "Stop"
$utf8Encoding = New-Object System.Text.UTF8Encoding($false)
[Console]::OutputEncoding = $utf8Encoding
$OutputEncoding = $utf8Encoding
$mutex = New-Object System.Threading.Mutex($false, "Local\AiChat-Conversation-Adversarial")
$ownsMutex = $false
try {
try {
$ownsMutex = $mutex.WaitOne(0)
} catch [System.Threading.AbandonedMutexException] {
$ownsMutex = $true
}
if (!$ownsMutex) {
Write-Host ">> Another conversation adversarial run is active; skipping overlap." -ForegroundColor Yellow
exit 0
}
$root = Split-Path -Parent $PSScriptRoot
$logRoot = Join-Path $root "logs\conversation"
if (!(Test-Path $logRoot)) {
New-Item -ItemType Directory -Path $logRoot -Force | Out-Null
}
$timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
$logFile = Join-Path $logRoot "conversation-adversarial-$timestamp.log"
$summaryFile = Join-Path $logRoot "conversation-adversarial-$timestamp.summary.json"
$testScript = Join-Path $root "backend\tests\conversation_adversarial_regression.php"
Write-Host ">> Running $Rounds adversarial conversation rounds" -ForegroundColor Cyan
& php $testScript $Rounds $summaryFile 2>&1 | ForEach-Object {
$line = [string]$_
Write-Host $line
Add-Content -Path $logFile -Value $line -Encoding UTF8
}
$exitCode = $LASTEXITCODE
if ($exitCode -ne 0) {
Write-Error "Conversation adversarial test failed with exit code $exitCode. Log: $logFile"
exit $exitCode
}
Write-Host ">> Conversation adversarial test passed. Log: $logFile" -ForegroundColor Green
} finally {
if ($ownsMutex) {
$mutex.ReleaseMutex()
}
$mutex.Dispose()
}
+87
View File
@@ -0,0 +1,87 @@
param(
[ValidateRange(1, 1000000)]
[int]$Rounds = 1000
)
$ErrorActionPreference = "Stop"
$utf8Encoding = New-Object System.Text.UTF8Encoding($false)
[Console]::OutputEncoding = $utf8Encoding
$OutputEncoding = $utf8Encoding
$mutex = New-Object System.Threading.Mutex($false, "Local\AiChat-Stability-Suite")
$ownsMutex = $false
try {
try {
$ownsMutex = $mutex.WaitOne(0)
} catch [System.Threading.AbandonedMutexException] {
$ownsMutex = $true
}
if (!$ownsMutex) {
Write-Host ">> Another stability run is already active; skipping this overlapping run." -ForegroundColor Yellow
exit 0
}
$root = Split-Path -Parent $PSScriptRoot
$logRoot = Join-Path $root "logs\stability"
if (!(Test-Path $logRoot)) {
New-Item -ItemType Directory -Path $logRoot -Force | Out-Null
}
$timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
$logFile = Join-Path $logRoot "stability-$timestamp.log"
$summaryFile = Join-Path $logRoot "stability-$timestamp.summary.json"
function Invoke-StabilitySuite {
param(
[string]$SuiteName
)
$testScript = Join-Path $root "backend\tests\stability_1000_round.php"
Write-Host ">> Running $SuiteName suite ($Rounds rounds)" -ForegroundColor Cyan
Add-Content -Path $logFile -Value "===== $SuiteName =====" -Encoding UTF8
# Windows PowerShell wraps native stderr as ErrorRecord objects. With the
# script-wide Stop preference, a failing suite used to abort this runner
# before the exit code, remaining suites, and JSON summary were recorded.
$previousErrorActionPreference = $ErrorActionPreference
try {
$ErrorActionPreference = "Continue"
& php $testScript $Rounds $SuiteName 2>&1 | ForEach-Object {
$line = [string]$_
Write-Host $line
Add-Content -Path $logFile -Value $line -Encoding UTF8
}
$exitCode = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previousErrorActionPreference
}
Add-Content -Path $logFile -Value "" -Encoding UTF8
return [PSCustomObject]@{
suite = $SuiteName
requestedRounds = $Rounds
exitCode = $exitCode
completedAt = (Get-Date).ToString("s")
}
}
$summary = @()
foreach ($suite in @("agent", "image", "llm")) {
$summary += Invoke-StabilitySuite -SuiteName $suite
}
$summary | ConvertTo-Json -Depth 4 | Set-Content -Path $summaryFile -Encoding UTF8
$failedSuites = @($summary | Where-Object { $_.exitCode -ne 0 })
if ($failedSuites.Count -gt 0) {
Write-Error "Stability run failed in $($failedSuites.Count) suite(s). Log: $logFile"
exit 1
}
Write-Host ">> Stability suites completed. Log: $logFile" -ForegroundColor Green
} finally {
if ($ownsMutex) {
$mutex.ReleaseMutex()
}
$mutex.Dispose()
}