Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

chat-client-identity.test.ts

98 lines2.9 KB

1import { afterEach, describe, expect, it, vi } from 'vitest'
2import { ChatClient } from '../src/chat-client'
3import { createMockPersistence, createTextChunks } from './test-utils'
4import type {
5 ConnectConnectionAdapter,
6 RunAgentInputContext,
7} from '../src/connection-adapters'
8​
9function createCapturingAdapter(chunks = createTextChunks('ok')): {
10 runContexts: Array<RunAgentInputContext>
11 adapter: ConnectConnectionAdapter
12} {
13 const runContexts: Array<RunAgentInputContext> = []
14 return {
15 runContexts,
16 adapter: {
17 async *connect(_messages, _data, abortSignal, runContext) {
18 if (runContext) {
19 runContexts.push(runContext)
20 }
21 for (const chunk of chunks) {
22 if (abortSignal?.aborted) {
23 return
24 }
25 yield chunk
26 }
27 },
28 },
29 }
31​
32describe('ChatClient identity', () => {
33 afterEach(() => {
34 vi.unstubAllGlobals()
35 vi.restoreAllMocks()
36 })
37​
38 it('does not call crypto.randomUUID or Math.random in the constructor', () => {
39 const randomUUID = vi.fn(() => {
40 throw new Error('crypto.randomUUID during construct')
41 })
42 vi.stubGlobal('crypto', { randomUUID })
43 const mathRandom = vi.spyOn(Math, 'random')
44​
45 expect(() => {
46 new ChatClient({
47 connection: createCapturingAdapter().adapter,
48 })
49 }).not.toThrow()
50​
51 expect(randomUUID).not.toHaveBeenCalled()
52 expect(mathRandom).not.toHaveBeenCalled()
53 })
54​
55 it('mints a thread id on first send when none is provided, and reuses it', async () => {
56 const { adapter, runContexts } = createCapturingAdapter()
57 const client = new ChatClient({ connection: adapter })
58​
59 await client.sendMessage('first')
60 await client.sendMessage('second')
61​
62 expect(runContexts).toHaveLength(2)
63 expect(runContexts[0]?.threadId).toMatch(/^thread-/)
64 expect(runContexts[1]?.threadId).toBe(runContexts[0]?.threadId)
65 })
66​
67 it('uses the provided threadId on the wire', async () => {
68 const { adapter, runContexts } = createCapturingAdapter()
69 const client = new ChatClient({
70 connection: adapter,
71 threadId: 'support-42',
72 })
73​
74 await client.sendMessage('hello')
75​
76 expect(runContexts[0]?.threadId).toBe('support-42')
77 })
78​
79 it('throws when persistence is set without a threadId', () => {
80 expect(() => {
81 // @ts-expect-error threadId is required whenever persistence is on
82 new ChatClient({
83 connection: createCapturingAdapter().adapter,
84 persistence: createMockPersistence(),
85 })
86 }).toThrow(/persistence needs a stable `threadId`/)
87 })
88​
89 it('throws when persistence: true is set without a threadId', () => {
90 expect(() => {
91 // @ts-expect-error threadId is required whenever persistence is on
92 new ChatClient({
93 connection: createCapturingAdapter().adapter,
94 persistence: true,
95 })
96 }).toThrow(/persistence needs a stable `threadId`/)
97 })
98})