Open History to see the last commit
1import { useEffect, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
4import { toolDefinition } from '@tanstack/ai'
5import { z } from 'zod'
6
7/**
8 * Client half of the issue #1058 harness.
9 *
10 * `persistence: true` + a `threadId` from the URL. The spec reloads while the
11 * first run is held open. On remount the client hydrates `activeRun` and tails
12 * it with `joinRun`. The client tool polls `ALLOW_TOOL_KEY` and only finishes
13 * after remount, so the dying first page cannot drain a live continuation.
14 */
15
16const ALLOW_TOOL_KEY = 'e2e-join-run-client-tool-allow'
17const connection = fetchServerSentEvents('/api/join-run-client-tool')
18
19const lookup = toolDefinition({
20 name: 'lookup',
21 description: 'Look up',
22 inputSchema: z.object({ query: z.string() }),
23 outputSchema: z.object({ answer: z.number() }),
24}).client(async () => {
25 const deadline = Date.now() + 60_000
26 while (sessionStorage.getItem(ALLOW_TOOL_KEY) !== '1') {
27 if (Date.now() > deadline) {
28 throw new Error('client tool was not allowed')
29 }
30 await new Promise((resolve) => setTimeout(resolve, 20))
31 }
32 return { answer: 42 }
33})
34
35export const Route = createFileRoute('/join-run-client-tool')({
36 component: JoinRunClientToolPage,
37 validateSearch: (search: Record<string, unknown>) => ({
38 threadId:
39 typeof search.threadId === 'string' && search.threadId.length > 0
40 ? search.threadId
41 : 'join-run-client-tool-thread',
42 }),
43})
44
45function JoinRunClientToolPage() {
46 const { threadId } = Route.useSearch()
47 const { messages, sendMessage, isLoading } = useChat({
48 threadId,
49 connection,
50 persistence: true,
51 tools: [lookup],
52 })
53
54 const [input, setInput] = useState('')
55 const [hydrated, setHydrated] = useState(false)
56 useEffect(() => setHydrated(true), [])
57
58 const assistantText = messages
59 .filter((message) => message.role === 'assistant')
60 .flatMap((message) =>
61 message.parts.flatMap((part) =>
62 part.type === 'text' ? [part.content] : [],
63 ),
64 )
65 .join('')
66
67 const toolPending = messages.some((message) =>
68 message.parts.some((part) => {
69 if (part.type !== 'tool-call' || part.name !== 'lookup') return false
70 return part.output === undefined
71 }),
72 )
73 const toolRan = messages.some((message) =>
74 message.parts.some((part) => {
75 if (part.type !== 'tool-call' || part.name !== 'lookup') return false
76 return part.output !== undefined
77 }),
78 )
79
80 const handleSubmit = () => {
81 const text = input.trim()
82 if (!text) return
83 setInput('')
84 void sendMessage(text)
85 }
86
87 return (
88 <div data-testid="join-run-client-tool-page" style={{ padding: 16 }}>
89 {hydrated ? <div data-testid="hydration-marker" /> : null}
90 <div data-testid="assistant-text">{assistantText || 'none'}</div>
91 <div data-testid="client-tool-pending">
92 {toolPending ? 'true' : 'false'}
93 </div>
94 <div data-testid="client-tool-ran">{toolRan ? 'true' : 'false'}</div>
95
96 <div data-testid="message-list">
97 {messages.map((message) => (
98 <div
99 key={message.id}
100 data-testid={
101 message.role === 'user' ? 'user-message' : 'assistant-message'
102 }
103 >
104 {message.parts.map((part, index) =>
105 part.type === 'text' ? (
106 <span key={`${message.id}-${index}`}>{part.content}</span>
107 ) : null,
108 )}
109 </div>
110 ))}
111 </div>
112
113 {isLoading ? (
114 <div data-testid="loading-indicator">Generating...</div>
115 ) : null}
116
117 <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
118 <input
119 data-testid="chat-input"
120 type="text"
121 value={input}
122 onChange={(e) => setInput(e.target.value)}
123 onKeyDown={(e) => {
124 if (e.key === 'Enter' && !e.shiftKey) {
125 e.preventDefault()
126 handleSubmit()
127 }
128 }}
129 placeholder="Type a message..."
130 />
131 <button
132 data-testid="send-button"
133 onClick={handleSubmit}
134 disabled={!input.trim()}
135 >
136 Send
137 </button>
138 </div>
139 </div>
140 )
141}