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

use-chat-byok.test.ts

100 lines2.9 KB

1import { EventType } from '@tanstack/ai'
2import { defineByok, memoryStorage } from '@tanstack/ai-client/byok'
3import { act, renderHook } from '@testing-library/react'
4import { describe, expect, it, vi } from 'vitest'
5import { useChat } from '../src/use-chat'
6import type {
7 ConnectConnectionAdapter,
8 RunAgentInputContext,
9} from '@tanstack/ai-client'
10import type { ModelMessage, StreamChunk } from '@tanstack/ai'
11import type { UIMessage } from '../src/types'
12​
13const RAW_KEY = 'sk-live-secret'
14​
15function runFinished(): StreamChunk {
16 return {
17 type: EventType.RUN_FINISHED,
18 runId: 'run-1',
19 threadId: 'thread-1',
20 model: 'gpt-5.5',
21 timestamp: Date.now(),
22 finishReason: 'stop',
23 }
25​
26function recordingConnection(record: {
27 headers?: Record<string, string>
28 data?: Record<string, unknown>
29}): ConnectConnectionAdapter {
30 const connect = vi.fn(async function* (
31 _messages: Array<UIMessage> | Array<ModelMessage>,
32 data?: Record<string, unknown>,
33 _abortSignal?: AbortSignal,
34 runContext?: RunAgentInputContext,
35 ) {
36 record.headers = runContext?.headers
37 record.data = data
38 yield runFinished()
39 })
40 return { connect }
42​
43describe('useChat byok', () => {
44 it('stamps x-byok headers and keeps the key out of the body', async () => {
45 const byok = defineByok({ storage: memoryStorage() })
46 await byok.update('openai', RAW_KEY)
47 const record: {
48 headers?: Record<string, string>
49 data?: Record<string, unknown>
50 } = {}
51​
52 const { result } = renderHook(() =>
53 useChat({
54 threadId: 'thread-1',
55 connection: recordingConnection(record),
56 byok,
57 forwardedProps: { provider: 'openai', model: 'gpt-5.5' },
58 }),
59 )
60​
61 await act(async () => {
62 await result.current.sendMessage('Hello')
63 })
64​
65 expect(record.headers).toEqual({ 'x-byok-openai': RAW_KEY })
66 expect(record.data).toEqual({ provider: 'openai', model: 'gpt-5.5' })
67 expect(JSON.stringify(record.data)).not.toContain(RAW_KEY)
68 })
69​
70 it('uses the latest byokProvider after a rerender', async () => {
71 const byok = defineByok({ storage: memoryStorage() })
72 await byok.update('openai', RAW_KEY)
73 await byok.update('anthropic', 'sk-anthropic-secret')
74 const record: {
75 headers?: Record<string, string>
76 data?: Record<string, unknown>
77 } = {}
78​
79 const { result, rerender } = renderHook(
80 ({ provider }: { provider: 'openai' | 'anthropic' }) =>
81 useChat({
82 threadId: 'thread-1',
83 connection: recordingConnection(record),
84 byok,
85 byokProvider: () => provider,
86 }),
87 { initialProps: { provider: 'openai' as 'openai' | 'anthropic' } },
88 )
89​
90 rerender({ provider: 'anthropic' })
91​
92 await act(async () => {
93 await result.current.sendMessage('Hello')
94 })
95​
96 expect(record.headers).toEqual({
97 'x-byok-anthropic': 'sk-anthropic-secret',
98 })
99 })
100})