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

activity-test.tsx

106 lines3.2 KB

1import { useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
4​
5/**
6 * Harness page for AG-UI activity. `/api/activity-test` yields live
7 * ACTIVITY_SNAPSHOT / ACTIVITY_DELTA (default) or a MESSAGES_SNAPSHOT that
8 * already contains an ActivityMessage (`?mode=snapshot`).
9 */
10export const Route = createFileRoute('/activity-test')({
11 component: ActivityTestPage,
12 validateSearch: (search: Record<string, unknown>) => ({
13 mode:
14 search.mode === 'snapshot' ? ('snapshot' as const) : ('live' as const),
15 }),
16})
17​
18function ActivityTestPage() {
19 const { mode } = Route.useSearch()
20 const [input, setInput] = useState('')
21 const { messages, sendMessage, isLoading } = useChat({
22 threadId: mode === 'snapshot' ? 'activity-snapshot' : 'activity-live',
23 connection: fetchServerSentEvents(
24 mode === 'snapshot'
25 ? '/api/activity-test?mode=snapshot'
26 : '/api/activity-test',
27 ),
28 })
29​
30 const handleSubmit = () => {
31 const text = input.trim()
32 if (!text) return
33 setInput('')
34 void sendMessage(text)
35 }
36​
37 return (
38 <div data-testid="activity-test-page" style={{ padding: 16 }}>
39 <div data-testid="message-list">
40 {messages.map((message) => {
41 if (message.role === 'activity') {
42 const part = message.parts[0]
43 const content =
44 part && part.type === 'activity'
45 ? JSON.stringify(part.content)
46 : ''
47 const activityType =
48 part && part.type === 'activity' ? part.activityType : ''
49 return (
50 <div
51 key={message.id}
52 data-testid="activity-message"
53 data-activity-id={message.id}
54 data-activity-type={activityType}
55 >
56 <span data-testid="activity-content">{content}</span>
57 </div>
58 )
59 }
60 return (
61 <div
62 key={message.id}
63 data-testid={
64 message.role === 'user' ? 'user-message' : 'assistant-message'
65 }
66 >
67 {message.parts.map((part, index) =>
68 part.type === 'text' ? (
69 <span key={`${message.id}-${index}`} data-testid="text-part">
70 {part.content}
71 </span>
72 ) : null,
73 )}
74 </div>
75 )
76 })}
77 </div>
78​
79 {isLoading && <div data-testid="loading-indicator">Generating...</div>}
80​
81 <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
82 <input
83 data-testid="chat-input"
84 type="text"
85 value={input}
86 onChange={(event) => setInput(event.target.value)}
87 onKeyDown={(event) => {
88 if (event.key === 'Enter' && !event.shiftKey) {
89 event.preventDefault()
90 handleSubmit()
91 }
92 }}
93 placeholder="Type a message..."
94 />
95 <button
96 data-testid="send-button"
97 type="button"
98 onClick={handleSubmit}
99 disabled={isLoading || !input.trim()}
100 >
101 Send
102 </button>
103 </div>
104 </div>
105 )