initial commit

This commit is contained in:
2026-10-16 21:39:08 +08:00
commit 1a9220364b
32 changed files with 6380 additions and 0 deletions
+212
View File
@@ -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
},
},
})
+177
View File
@@ -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()
},
},
})
+84
View File
@@ -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')
},
},
})