Open History to see the last commit
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 }
30}
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 threadId: 'thread-1',
48 connection: createCapturingAdapter().adapter,
49 })
50 }).not.toThrow()
51
52 expect(randomUUID).not.toHaveBeenCalled()
53 expect(mathRandom).not.toHaveBeenCalled()
54 })
55
56 it('uses the provided threadId on the wire', async () => {
57 const { adapter, runContexts } = createCapturingAdapter()
58 const client = new ChatClient({
59 connection: adapter,
60 threadId: 'support-42',
61 })
62
63 await client.sendMessage('hello')
64
65 expect(runContexts[0]?.threadId).toBe('support-42')
66 })
67
68 it.each([
69 ['empty', ''],
70 ['missing', undefined],
71 ['non-string', 42],
72 ])('throws when threadId is %s', (_label, threadId) => {
73 expect(() => {
74 new ChatClient({
75 connection: createCapturingAdapter().adapter,
76 threadId: threadId as never,
77 })
78 }).toThrow('ChatClient: threadId is required (a non-empty string).')
79 })
80
81 it('throws for an empty threadId even with persistence', () => {
82 expect(() => {
83 new ChatClient({
84 connection: createCapturingAdapter().adapter,
85 persistence: createMockPersistence(),
86 threadId: '',
87 })
88 }).toThrow('ChatClient: threadId is required (a non-empty string).')
89 })
90})