feat(chat): improve resilience and collapsible sidebar
问题描述:\n- 刷新页面、切后台或手机锁屏后,进行中的对话容易丢失,SSE 断开时前端还会插入假的错误气泡\n- 移动端首屏会话列表会短暂遮住聊天区\n- 桌面端侧栏无法折叠,在窄窗口和缩放场景占用过多横向空间\n\n复现路径:\n- 发起一轮对话,在模型仍在输出时刷新页面或锁屏后再回到页面\n- 在窄屏设备首次打开聊天页,观察会话列表首帧覆盖聊天内容\n- 在桌面端缩窄浏览器窗口,观察侧栏始终保持完整宽度\n\n修复思路:\n- 为 chat store 增加本地缓存、水合、in-flight 标记和轮询恢复,SSE 断开后静默从服务端回补真实结果\n- 将运行中指示统一到 isRunActive,让实时流式与恢复轮询共享同一状态\n- 在 ChatPanel 首帧同步读取媒体查询,避免移动端会话列表闪烁覆盖\n- 为侧栏增加可持久化的桌面折叠状态,并补充对应文案与回归测试
This commit is contained in:
@@ -0,0 +1,226 @@
|
||||
// @vitest-environment jsdom
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
|
||||
const mockChatApi = vi.hoisted(() => ({
|
||||
startRun: vi.fn(),
|
||||
streamRunEvents: vi.fn(),
|
||||
}))
|
||||
|
||||
const mockSessionsApi = vi.hoisted(() => ({
|
||||
fetchSessions: vi.fn(),
|
||||
fetchSession: vi.fn(),
|
||||
deleteSession: vi.fn(),
|
||||
renameSession: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/hermes/chat', () => mockChatApi)
|
||||
vi.mock('@/api/hermes/sessions', () => mockSessionsApi)
|
||||
|
||||
import { useChatStore } from '@/stores/hermes/chat'
|
||||
|
||||
function makeSummary(id: string, title = 'Session') {
|
||||
return {
|
||||
id,
|
||||
source: 'api_server',
|
||||
model: 'gpt-4o',
|
||||
title,
|
||||
started_at: 1710000000,
|
||||
ended_at: 1710000001,
|
||||
message_count: 1,
|
||||
tool_call_count: 0,
|
||||
input_tokens: 10,
|
||||
output_tokens: 20,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
reasoning_tokens: 0,
|
||||
billing_provider: 'openai',
|
||||
estimated_cost_usd: 0,
|
||||
actual_cost_usd: 0,
|
||||
cost_status: 'estimated',
|
||||
}
|
||||
}
|
||||
|
||||
function makeDetail(id: string, messages: Array<Record<string, any>>) {
|
||||
return {
|
||||
...makeSummary(id),
|
||||
messages,
|
||||
}
|
||||
}
|
||||
|
||||
async function flushPromises() {
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
}
|
||||
|
||||
describe('Chat Store', () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
vi.clearAllMocks()
|
||||
vi.useRealTimers()
|
||||
window.localStorage.clear()
|
||||
mockSessionsApi.fetchSessions.mockResolvedValue([])
|
||||
mockSessionsApi.fetchSession.mockResolvedValue(null)
|
||||
mockSessionsApi.deleteSession.mockResolvedValue(true)
|
||||
mockSessionsApi.renameSession.mockResolvedValue(true)
|
||||
mockChatApi.startRun.mockResolvedValue({ run_id: 'run-1', status: 'queued' })
|
||||
mockChatApi.streamRunEvents.mockImplementation(() => ({
|
||||
abort: vi.fn(),
|
||||
}))
|
||||
})
|
||||
|
||||
it('hydrates cached active session immediately and preserves local-only sessions after refresh', async () => {
|
||||
const cachedSession = {
|
||||
id: 'local-1',
|
||||
title: 'Local Draft',
|
||||
source: 'api_server',
|
||||
messages: [],
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
}
|
||||
const cachedMessages = [
|
||||
{ id: 'm1', role: 'user', content: 'draft', timestamp: 1 },
|
||||
]
|
||||
|
||||
window.localStorage.setItem('hermes_active_session', 'local-1')
|
||||
window.localStorage.setItem('hermes_sessions_cache_v1', JSON.stringify([cachedSession]))
|
||||
window.localStorage.setItem('hermes_session_msgs_v1_local-1', JSON.stringify(cachedMessages))
|
||||
|
||||
mockSessionsApi.fetchSessions.mockResolvedValue([makeSummary('remote-1', 'Remote Session')])
|
||||
mockSessionsApi.fetchSession.mockResolvedValue(null)
|
||||
|
||||
const store = useChatStore()
|
||||
|
||||
expect(store.activeSessionId).toBe('local-1')
|
||||
expect(store.messages.map(m => m.content)).toEqual(['draft'])
|
||||
|
||||
await flushPromises()
|
||||
|
||||
expect(store.sessions.map(s => s.id)).toEqual(['local-1', 'remote-1'])
|
||||
expect(store.activeSession?.id).toBe('local-1')
|
||||
expect(store.messages.map(m => m.content)).toEqual(['draft'])
|
||||
})
|
||||
|
||||
it('persists the user message immediately before any SSE delta arrives', async () => {
|
||||
const store = useChatStore()
|
||||
|
||||
await flushPromises()
|
||||
await store.sendMessage('hello world')
|
||||
|
||||
const sid = store.activeSessionId
|
||||
expect(sid).toBeTruthy()
|
||||
expect(window.localStorage.getItem('hermes_active_session')).toBe(sid)
|
||||
|
||||
const cachedMessages = JSON.parse(
|
||||
window.localStorage.getItem(`hermes_session_msgs_v1_${sid}`) || '[]',
|
||||
)
|
||||
expect(cachedMessages).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
role: 'user',
|
||||
content: 'hello world',
|
||||
}),
|
||||
]),
|
||||
)
|
||||
})
|
||||
|
||||
it('silently refreshes from server on SSE error instead of appending a fake error bubble', async () => {
|
||||
vi.useFakeTimers()
|
||||
|
||||
window.localStorage.setItem('hermes_active_session', 'sess-1')
|
||||
window.localStorage.setItem(
|
||||
'hermes_sessions_cache_v1',
|
||||
JSON.stringify([
|
||||
{
|
||||
id: 'sess-1',
|
||||
title: 'Recovered Chat',
|
||||
source: 'api_server',
|
||||
messages: [],
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
},
|
||||
]),
|
||||
)
|
||||
window.localStorage.setItem(
|
||||
'hermes_session_msgs_v1_sess-1',
|
||||
JSON.stringify([
|
||||
{ id: 'old-user', role: 'user', content: 'old prompt', timestamp: 1 },
|
||||
]),
|
||||
)
|
||||
|
||||
mockSessionsApi.fetchSessions.mockResolvedValue([makeSummary('sess-1', 'Recovered Chat')])
|
||||
|
||||
let fetchSessionCalls = 0
|
||||
mockSessionsApi.fetchSession.mockImplementation(async () => {
|
||||
fetchSessionCalls += 1
|
||||
if (fetchSessionCalls === 1) return null
|
||||
return makeDetail('sess-1', [
|
||||
{
|
||||
id: 1,
|
||||
session_id: 'sess-1',
|
||||
role: 'user',
|
||||
content: 'old prompt',
|
||||
tool_call_id: null,
|
||||
tool_calls: null,
|
||||
tool_name: null,
|
||||
timestamp: 1710000000,
|
||||
token_count: null,
|
||||
finish_reason: null,
|
||||
reasoning: null,
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
session_id: 'sess-1',
|
||||
role: 'user',
|
||||
content: 'check this',
|
||||
tool_call_id: null,
|
||||
tool_calls: null,
|
||||
tool_name: null,
|
||||
timestamp: 1710000001,
|
||||
token_count: null,
|
||||
finish_reason: null,
|
||||
reasoning: null,
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
session_id: 'sess-1',
|
||||
role: 'assistant',
|
||||
content: 'final answer',
|
||||
tool_call_id: null,
|
||||
tool_calls: null,
|
||||
tool_name: null,
|
||||
timestamp: 1710000002,
|
||||
token_count: null,
|
||||
finish_reason: 'stop',
|
||||
reasoning: null,
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
mockChatApi.streamRunEvents.mockImplementation((
|
||||
_runId: string,
|
||||
_onEvent: (event: unknown) => void,
|
||||
_onDone: () => void,
|
||||
onError: (err: Error) => void,
|
||||
) => {
|
||||
setTimeout(() => {
|
||||
onError(new Error('SSE connection error'))
|
||||
}, 0)
|
||||
return { abort: vi.fn() }
|
||||
})
|
||||
|
||||
const store = useChatStore()
|
||||
await flushPromises()
|
||||
await store.sendMessage('check this')
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
await flushPromises()
|
||||
|
||||
await vi.advanceTimersByTimeAsync(9000)
|
||||
await flushPromises()
|
||||
|
||||
expect(store.messages.some(m => m.role === 'system' && m.content.includes('SSE connection error'))).toBe(false)
|
||||
expect(store.messages.some(m => m.role === 'assistant' && m.content === 'final answer')).toBe(true)
|
||||
expect(store.isRunActive).toBe(false)
|
||||
expect(window.localStorage.getItem('hermes_in_flight_v1_sess-1')).toBeNull()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user