Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { ByokMissingError } from '@tanstack/ai/byok'
3import { defineByok, memoryStorage } from '../src/byok'
4import { ChatClient } from '../src/chat-client'
5import type { ResumableConnectConnectionAdapter } from '../src/connection-adapters'
6
7/**
8 * `persistence: true` loads the thread from the server on mount. When that
9 * hydrate GET fails, the failure used to be swallowed by a bare `catch {
10 * return }` in `hydrateFromServer` — `onError` never fired, `error` stayed
11 * undefined, and `status` stayed `ready` with zero messages, indistinguishable
12 * from a genuinely empty thread. `failHydration` now surfaces it, mirroring
13 * `GenerationClient.failHydration`.
14 *
15 * https://github.com/TanStack/ai/issues/1331
16 */
17describe('mount hydration failure is surfaced (persistence: true)', () => {
18 function mounted(options: ConstructorParameters<typeof ChatClient>[0]) {
19 const client = new ChatClient(options)
20 client.attach()
21 return client
22 }
23
24 it('reports a thrown hydrate error via onError / error / status', async () => {
25 const onError = vi.fn()
26 const errors: Array<Error | undefined> = []
27 const statuses: Array<string> = []
28
29 const connection: ResumableConnectConnectionAdapter = {
30 connect: async function* () {},
31 joinRun: async function* () {},
32 hydrate: () => Promise.reject(new Error('server returned 500')),
33 }
34
35 const client = mounted({
36 threadId: 't1',
37 connection,
38 persistence: true,
39 onError,
40 onErrorChange: (e) => errors.push(e),
41 onStatusChange: (s) => statuses.push(s),
42 })
43
44 await vi.waitFor(() => {
45 expect(onError).toHaveBeenCalledTimes(1)
46 })
47 expect(onError).toHaveBeenCalledWith(
48 expect.objectContaining({ message: 'server returned 500' }),
49 )
50 expect(errors.at(-1)).toBeInstanceOf(Error)
51 expect(client.getError()?.message).toBe('server returned 500')
52 expect(client.getStatus()).toBe('error')
53 expect(statuses).toContain('error')
54
55 client.dispose()
56 })
57
58 it('stays silent when the view detached before the hydrate rejected', async () => {
59 const onError = vi.fn()
60 let rejectHydration: ((reason: unknown) => void) | undefined
61 const gate = new Promise<never>((_, reject) => {
62 rejectHydration = reject
63 })
64
65 const connection: ResumableConnectConnectionAdapter = {
66 connect: async function* () {},
67 joinRun: async function* () {},
68 hydrate: () => gate,
69 }
70
71 const client = mounted({
72 threadId: 't1',
73 connection,
74 persistence: true,
75 onError,
76 })
77
78 // View switch: detach (NOT dispose) while the hydrate GET is still in flight.
79 client.detach()
80 rejectHydration?.(new Error('server returned 500'))
81 await new Promise((resolve) => setTimeout(resolve, 10))
82
83 expect(onError).not.toHaveBeenCalled()
84 expect(client.getStatus()).not.toBe('error')
85
86 client.dispose()
87 })
88
89 it('triggers the BYOK key-request flow when hydrate throws ByokMissingError', async () => {
90 const byok = defineByok({ storage: memoryStorage() })
91 const onError = vi.fn()
92
93 const connection: ResumableConnectConnectionAdapter = {
94 connect: async function* () {},
95 joinRun: async function* () {},
96 hydrate: () => Promise.reject(new ByokMissingError('openai')),
97 }
98
99 const client = mounted({
100 threadId: 't1',
101 connection,
102 persistence: true,
103 byok,
104 onError,
105 })
106
107 await vi.waitFor(() => {
108 expect(onError).toHaveBeenCalledTimes(1)
109 })
110 expect(onError).toHaveBeenCalledWith(expect.any(ByokMissingError))
111 expect(byok.getSnapshot().prompt).toEqual({
112 provider: 'openai',
113 reason: 'missing',
114 })
115
116 client.dispose()
117 })
118
119 it('clears the hydration error when a later load succeeds', async () => {
120 let attempt = 0
121 const connection: ResumableConnectConnectionAdapter = {
122 connect: async function* () {},
123 joinRun: async function* () {},
124 hydrate: () =>
125 ++attempt === 1
126 ? Promise.reject(new Error('server returned 500'))
127 : Promise.resolve({
128 messages: [],
129 activeRun: null,
130 interrupts: null,
131 }),
132 }
133
134 const client = mounted({ threadId: 't1', connection, persistence: true })
135 await vi.waitFor(() => {
136 expect(client.getStatus()).toBe('error')
137 })
138
139 // Retry: the view detaches and attaches again, and this load succeeds.
140 client.detach()
141 client.attach()
142 await vi.waitFor(() => {
143 expect(attempt).toBe(2)
144 expect(client.getError()).toBeUndefined()
145 })
146 expect(client.getStatus()).not.toBe('error')
147
148 client.dispose()
149 })
150
151 it('does not surface anything when hydration succeeds', async () => {
152 const onError = vi.fn()
153 const statuses: Array<string> = []
154
155 const connection: ResumableConnectConnectionAdapter = {
156 connect: async function* () {},
157 joinRun: async function* () {},
158 hydrate: () =>
159 Promise.resolve({ messages: [], activeRun: null, interrupts: null }),
160 }
161
162 const client = mounted({
163 threadId: 't1',
164 connection,
165 persistence: true,
166 onError,
167 onStatusChange: (s) => statuses.push(s),
168 })
169
170 await new Promise((resolve) => setTimeout(resolve, 10))
171
172 expect(onError).not.toHaveBeenCalled()
173 expect(client.getError()).toBeUndefined()
174 expect(client.getStatus()).not.toBe('error')
175 expect(statuses).not.toContain('error')
176
177 client.dispose()
178 })
179})