Open History to see the last commit
1import { readFileSync } from 'node:fs'
2import { fileURLToPath } from 'node:url'
3import { runInNewContext } from 'node:vm'
4
5import ts from 'typescript'
6import { describe, expect, it } from 'vitest'
7
8const routePath = fileURLToPath(
9 new URL(
10 '../src/frameworks/react/examples/events/assets/src/routes/api.remy-chat.ts',
11 import.meta.url,
12 ),
13)
14
15function loadRoute() {
16 const prompts: Array<Array<string>> = []
17 const routeModule: {
18 Route?: {
19 server: {
20 handlers: {
21 POST: (context: { request: Request }) => Promise<Response>
22 }
23 }
24 }
25 } = {}
26 const provider = (model: string) => ({ model })
27 const modules: Record<string, object> = {
28 '@tanstack/react-router': {
29 createFileRoute: () => (route: object) => route,
30 },
31 '@tanstack/ai': {
32 chat: (options: { systemPrompts: Array<string> }) => {
33 prompts.push(options.systemPrompts)
34 return []
35 },
36 maxIterations: () => () => true,
37 toServerSentEventsResponse: () => new Response('mock stream'),
38 },
39 '@tanstack/ai-anthropic': { anthropicText: provider },
40 '@tanstack/ai-openai': { openaiText: provider },
41 '@tanstack/ai-gemini': { geminiText: provider },
42 '@tanstack/ai-ollama': { ollamaText: provider },
43 '#/lib/conference-tools': {},
44 }
45 const compiled = ts.transpileModule(readFileSync(routePath, 'utf8'), {
46 compilerOptions: {
47 module: ts.ModuleKind.CommonJS,
48 target: ts.ScriptTarget.ES2022,
49 },
50 })
51 runInNewContext(compiled.outputText, {
52 exports: routeModule,
53 require: (name: string) => {
54 if (!(name in modules)) throw new Error(`Unexpected import: ${name}`)
55 return modules[name]
56 },
57 process: { env: {} },
58 Response,
59 AbortController,
60 console,
61 })
62 if (!routeModule.Route) throw new Error('Events route did not load')
63 return { post: routeModule.Route.server.handlers.POST, prompts }
64}
65
66async function requestContext(body: object) {
67 const route = loadRoute()
68 const response = await route.post({
69 request: new Request('http://localhost/api/remy-chat', {
70 method: 'POST',
71 body: JSON.stringify({ messages: [], threadId: 'conference', ...body }),
72 headers: { 'Content-Type': 'application/json' },
73 }),
74 })
75 return { response, prompts: route.prompts.flat().join('\n') }
76}
77
78describe('events chat page context', () => {
79 it('reads speaker and talk context from the transport forwardedProps', async () => {
80 const { response, prompts } = await requestContext({
81 forwardedProps: { speakerSlug: 'alice', talkSlug: 'pastry' },
82 })
83 expect(response.status).toBe(200)
84 expect(prompts).toContain('speaker with slug "alice"')
85 expect(prompts).toContain('session with slug "pastry"')
86 })
87
88 it('preserves clients that send top-level context', async () => {
89 const { prompts } = await requestContext({ speakerSlug: 'alice' })
90 expect(prompts).toContain('speaker with slug "alice"')
91 })
92
93 it('uses the current transport context when both payload shapes are present', async () => {
94 const { prompts } = await requestContext({
95 speakerSlug: 'old-speaker',
96 forwardedProps: { speakerSlug: 'current-speaker' },
97 })
98 expect(prompts).toContain('speaker with slug "current-speaker"')
99 expect(prompts).not.toContain('speaker with slug "old-speaker"')
100 })
101
102 it.each([
103 { forwardedProps: { speakerSlug: 'alice' }, talkSlug: 'pastry' },
104 { speakerSlug: 'alice', forwardedProps: { talkSlug: 'pastry' } },
105 ])('preserves both slugs in a mixed payload: %j', async (body) => {
106 const { prompts } = await requestContext(body)
107 expect(prompts).toContain('speaker with slug "alice"')
108 expect(prompts).toContain('session with slug "pastry"')
109 })
110
111 it('ignores non-string context instead of adding it to the prompt', async () => {
112 const { prompts } = await requestContext({
113 forwardedProps: { speakerSlug: { invalid: true }, talkSlug: ['invalid'] },
114 })
115 expect(prompts).not.toContain('CONTEXT:')
116 })
117
118 it('allows requests without page context', async () => {
119 const { response, prompts } = await requestContext({})
120 expect(response.status).toBe(200)
121 expect(prompts).not.toContain('CONTEXT:')
122 })
123
124 it('keeps the missing-thread response and does not start a chat', async () => {
125 const { response, prompts } = await requestContext({ threadId: '' })
126 expect(response.status).toBe(400)
127 expect(await response.json()).toEqual({ error: 'A threadId is required' })
128 expect(prompts).toBe('')
129 })
130})