|
| 1 | +import { act, cleanup, render } from '@testing-library/react' |
| 2 | +import { useEffect, useRef } from 'react' |
| 3 | +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' |
| 4 | + |
| 5 | +import type { ClientSessionState } from '@/app/types' |
| 6 | +import { assistantTextPart, chatMessageText, type ChatMessage } from '@/lib/chat-messages' |
| 7 | +import { createClientSessionState } from '@/lib/chat-runtime' |
| 8 | +import { setSessions } from '@/store/session' |
| 9 | +import type { SessionMessagesResponse, UsageStats } from '@/types/hermes' |
| 10 | + |
| 11 | +import { useSessionActions } from './use-session-actions' |
| 12 | + |
| 13 | +const mocks = vi.hoisted(() => ({ |
| 14 | + ensureGatewayProfile: vi.fn(async () => undefined), |
| 15 | + getProfiles: vi.fn(async () => ({ profiles: [] })), |
| 16 | + getSessionMessages: vi.fn<(...args: unknown[]) => Promise<SessionMessagesResponse>>(), |
| 17 | + setApiRequestProfile: vi.fn() |
| 18 | +})) |
| 19 | + |
| 20 | +vi.mock('@/hermes', async importOriginal => { |
| 21 | + const actual = await importOriginal<typeof import('@/hermes')>() |
| 22 | + |
| 23 | + return { |
| 24 | + ...actual, |
| 25 | + getProfiles: mocks.getProfiles, |
| 26 | + getSessionMessages: mocks.getSessionMessages, |
| 27 | + setApiRequestProfile: mocks.setApiRequestProfile |
| 28 | + } |
| 29 | +}) |
| 30 | + |
| 31 | +vi.mock('@/store/profile', async importOriginal => { |
| 32 | + const actual = await importOriginal<typeof import('@/store/profile')>() |
| 33 | + |
| 34 | + return { |
| 35 | + ...actual, |
| 36 | + ensureGatewayProfile: mocks.ensureGatewayProfile |
| 37 | + } |
| 38 | +}) |
| 39 | + |
| 40 | +interface HarnessHandle { |
| 41 | + resumeSession: (storedSessionId: string, replaceRoute?: boolean) => Promise<void> |
| 42 | +} |
| 43 | + |
| 44 | +function assistantMessage(id: string, text: string): ChatMessage { |
| 45 | + return { |
| 46 | + id, |
| 47 | + parts: [assistantTextPart(text)], |
| 48 | + role: 'assistant' |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +function cachedState(): ClientSessionState { |
| 53 | + return { |
| 54 | + ...createClientSessionState('stored-session-1', [assistantMessage('cached-assistant', 'stale window copy')]), |
| 55 | + storedSessionId: 'stored-session-1' |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +function requestGatewayMock(usage: UsageStats) { |
| 60 | + const impl = async <T,>(method: string) => { |
| 61 | + if (method === 'session.usage') { |
| 62 | + return usage as T |
| 63 | + } |
| 64 | + |
| 65 | + return {} as T |
| 66 | + } |
| 67 | + |
| 68 | + return vi.fn(impl) as unknown as <T>(method: string, params?: Record<string, unknown>) => Promise<T> |
| 69 | +} |
| 70 | + |
| 71 | +function Harness({ |
| 72 | + onReady, |
| 73 | + onSync, |
| 74 | + requestGateway |
| 75 | +}: { |
| 76 | + onReady: (handle: HarnessHandle) => void |
| 77 | + onSync: (sessionId: string, state: ClientSessionState) => void |
| 78 | + requestGateway: <T>(method: string, params?: Record<string, unknown>) => Promise<T> |
| 79 | +}) { |
| 80 | + const activeSessionIdRef = useRef<string | null>('runtime-session-1') |
| 81 | + const busyRef = useRef(false) |
| 82 | + const creatingSessionRef = useRef(false) |
| 83 | + const runtimeIdByStoredSessionIdRef = useRef(new Map([['stored-session-1', 'runtime-session-1']])) |
| 84 | + const selectedStoredSessionIdRef = useRef<string | null>('stored-session-1') |
| 85 | + const sessionStateByRuntimeIdRef = useRef(new Map([['runtime-session-1', cachedState()]])) |
| 86 | + |
| 87 | + const actions = useSessionActions({ |
| 88 | + activeSessionId: null, |
| 89 | + activeSessionIdRef, |
| 90 | + busyRef, |
| 91 | + creatingSessionRef, |
| 92 | + ensureSessionState: sessionId => sessionStateByRuntimeIdRef.current.get(sessionId) ?? cachedState(), |
| 93 | + getRouteToken: () => '/stored-session-1', |
| 94 | + navigate: vi.fn(), |
| 95 | + requestGateway, |
| 96 | + runtimeIdByStoredSessionIdRef, |
| 97 | + selectedStoredSessionId: null, |
| 98 | + selectedStoredSessionIdRef, |
| 99 | + sessionStateByRuntimeIdRef, |
| 100 | + syncSessionStateToView: (sessionId, state) => { |
| 101 | + onSync(sessionId, state) |
| 102 | + }, |
| 103 | + updateSessionState: (sessionId, updater) => { |
| 104 | + const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? cachedState() |
| 105 | + const next = updater(current) |
| 106 | + sessionStateByRuntimeIdRef.current.set(sessionId, next) |
| 107 | + onSync(sessionId, next) |
| 108 | + |
| 109 | + return next |
| 110 | + } |
| 111 | + }) |
| 112 | + |
| 113 | + useEffect(() => { |
| 114 | + onReady({ resumeSession: actions.resumeSession }) |
| 115 | + }, [actions.resumeSession, onReady]) |
| 116 | + |
| 117 | + return null |
| 118 | +} |
| 119 | + |
| 120 | +describe('useSessionActions resumeSession', () => { |
| 121 | + beforeEach(() => { |
| 122 | + setSessions(() => [ |
| 123 | + { |
| 124 | + ended_at: null, |
| 125 | + id: 'stored-session-1', |
| 126 | + input_tokens: 0, |
| 127 | + is_active: true, |
| 128 | + last_active: 0, |
| 129 | + message_count: 2, |
| 130 | + model: null, |
| 131 | + output_tokens: 0, |
| 132 | + preview: 'fresh from window A', |
| 133 | + profile: 'builder', |
| 134 | + source: 'cli', |
| 135 | + started_at: 0, |
| 136 | + title: 'Session 1', |
| 137 | + tool_call_count: 0 |
| 138 | + } |
| 139 | + ]) |
| 140 | + mocks.ensureGatewayProfile.mockClear() |
| 141 | + mocks.getProfiles.mockClear() |
| 142 | + mocks.getSessionMessages.mockReset() |
| 143 | + mocks.setApiRequestProfile.mockClear() |
| 144 | + }) |
| 145 | + |
| 146 | + afterEach(() => { |
| 147 | + cleanup() |
| 148 | + vi.restoreAllMocks() |
| 149 | + }) |
| 150 | + |
| 151 | + it('rehydrates a cached session from stored messages so another window sees the latest transcript', async () => { |
| 152 | + mocks.getSessionMessages.mockResolvedValue({ |
| 153 | + messages: [{ content: 'fresh from window A', role: 'assistant', timestamp: 1 }], |
| 154 | + session_id: 'stored-session-1' |
| 155 | + }) |
| 156 | + |
| 157 | + const requestGateway = requestGatewayMock({ calls: 1, input: 2, output: 3, total: 5 }) |
| 158 | + const syncs: ClientSessionState[] = [] |
| 159 | + let handle: HarnessHandle | null = null |
| 160 | + |
| 161 | + render( |
| 162 | + <Harness |
| 163 | + onReady={next => { |
| 164 | + handle = next |
| 165 | + }} |
| 166 | + onSync={(_sessionId, state) => { |
| 167 | + syncs.push(state) |
| 168 | + }} |
| 169 | + requestGateway={requestGateway} |
| 170 | + /> |
| 171 | + ) |
| 172 | + |
| 173 | + await act(async () => { |
| 174 | + await handle!.resumeSession('stored-session-1') |
| 175 | + }) |
| 176 | + |
| 177 | + expect(mocks.ensureGatewayProfile).toHaveBeenCalledWith('builder') |
| 178 | + expect(mocks.getSessionMessages).toHaveBeenCalledWith('stored-session-1', 'builder') |
| 179 | + expect(syncs).toHaveLength(2) |
| 180 | + expect(chatMessageText(syncs.at(-1)!.messages[0]!)).toBe('fresh from window A') |
| 181 | + expect(requestGateway).toHaveBeenCalledWith('session.usage', { session_id: 'runtime-session-1' }) |
| 182 | + }) |
| 183 | + |
| 184 | + it('keeps the warm cache visible when the stored rehydrate fails', async () => { |
| 185 | + mocks.getSessionMessages.mockRejectedValue(new Error('state.db busy')) |
| 186 | + |
| 187 | + const requestGateway = requestGatewayMock({ calls: 0, input: 0, output: 0, total: 0 }) |
| 188 | + const syncs: ClientSessionState[] = [] |
| 189 | + let handle: HarnessHandle | null = null |
| 190 | + |
| 191 | + render( |
| 192 | + <Harness |
| 193 | + onReady={next => { |
| 194 | + handle = next |
| 195 | + }} |
| 196 | + onSync={(_sessionId, state) => { |
| 197 | + syncs.push(state) |
| 198 | + }} |
| 199 | + requestGateway={requestGateway} |
| 200 | + /> |
| 201 | + ) |
| 202 | + |
| 203 | + await act(async () => { |
| 204 | + await handle!.resumeSession('stored-session-1') |
| 205 | + }) |
| 206 | + |
| 207 | + expect(mocks.getSessionMessages).toHaveBeenCalledWith('stored-session-1', 'builder') |
| 208 | + expect(syncs).toHaveLength(1) |
| 209 | + expect(chatMessageText(syncs[0]!.messages[0]!)).toBe('stale window copy') |
| 210 | + }) |
| 211 | +}) |
0 commit comments