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

tools-test.tsx

815 lines24.8 KB

1import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
4import { modelMessagesToUIMessages, toolDefinition } from '@tanstack/ai'
5import { z } from 'zod'
6import type { ModelMessage, ToolCallPart } from '@tanstack/ai'
7import type { UIMessage } from '@tanstack/ai-react'
8import { parseAimockPort } from '@/lib/devtools-test'
9import { SCENARIO_LIST, STOP_CLIENT_TOOL_MESSAGE } from '@/lib/tools-test-tools'
10​
11/**
12 * Event log entry for tracking tool execution flow
13 */
14interface ToolEvent {
15 timestamp: number
16 type:
17 | 'execution-start'
18 | 'execution-complete'
19 | 'approval-granted'
20 | 'approval-denied'
21 | 'error'
22 | 'custom-event'
23 toolName: string
24 toolCallId?: string
25 details?: string
27​
28type ClientRuntimeContext = {
29 userId: string
30 tenantId: string
31 source: string
33​
34const clientRuntimeContext: ClientRuntimeContext = {
35 userId: 'client-user-context',
36 tenantId: 'client-tenant-context',
37 source: 'client-local',
39​
40/**
41 * Client-side tool definitions with execute functions
42 * These track execution for testing purposes
43 */
44function createTrackedTools(
45 addEvent: (event: Omit<ToolEvent, 'timestamp'>) => void,
46) {
47 const readClientContextTool = toolDefinition({
48 name: 'read_client_context',
49 description: 'Read the typed runtime context provided by the client',
50 inputSchema: z.object({}),
51 outputSchema: z.object({
52 userId: z.string(),
53 tenantId: z.string(),
54 source: z.string(),
55 }),
56 }).client<ClientRuntimeContext>(async (_args, context) => {
57 addEvent({
58 type: 'execution-start',
59 toolName: 'read_client_context',
60 details: context.context.userId,
61 })
62​
63 addEvent({
64 type: 'execution-complete',
65 toolName: 'read_client_context',
66 details: `${context.context.userId}/${context.context.tenantId}`,
67 })
68​
69 return {
70 userId: context.context.userId,
71 tenantId: context.context.tenantId,
72 source: context.context.source,
73 }
74 })
75​
76 const showNotificationTool = toolDefinition({
77 name: 'show_notification',
78 description: 'Show a notification to the user',
79 inputSchema: z.object({
80 message: z.string(),
81 type: z.enum(['info', 'warning', 'error']),
82 }),
83 outputSchema: z.object({
84 displayed: z.boolean(),
85 timestamp: z.number(),
86 }),
87 }).client(async (args) => {
88 addEvent({
89 type: 'execution-start',
90 toolName: 'show_notification',
91 details: args.message,
92 })
93​
94 await new Promise((resolve) =>
95 setTimeout(
96 resolve,
97 args.message === STOP_CLIENT_TOOL_MESSAGE ? 1000 : 50,
98 ),
99 )
100​
101 addEvent({
102 type: 'execution-complete',
103 toolName: 'show_notification',
104 details: args.message,
105 })
106​
107 return {
108 displayed: true,
109 timestamp: Date.now(),
110 }
111 })
112​
113 const displayChartTool = toolDefinition({
114 name: 'display_chart',
115 description: 'Display a chart on the screen',
116 inputSchema: z.object({
117 type: z.enum(['bar', 'line', 'pie']),
118 data: z.array(z.number()),
119 }),
120 outputSchema: z.object({
121 rendered: z.boolean(),
122 chartId: z.string(),
123 }),
124 }).client(async (args) => {
125 addEvent({
126 type: 'execution-start',
127 toolName: 'display_chart',
128 details: args.type,
129 })
130​
131 // Simulate async work
132 await new Promise((r) => setTimeout(r, 50))
133​
134 addEvent({
135 type: 'execution-complete',
136 toolName: 'display_chart',
137 details: args.type,
138 })
139​
140 return {
141 rendered: true,
142 chartId: `chart-${Date.now()}`,
143 }
144 })
145​
146 const failClientTool = toolDefinition({
147 name: 'fail_client_tool',
148 description: 'Fail while executing in the client',
149 inputSchema: z.object({}),
150 outputSchema: z.object({ completed: z.boolean() }),
151 }).client(async () => {
152 addEvent({
153 type: 'execution-start',
154 toolName: 'fail_client_tool',
155 })
156 throw new Error('Client tool failed')
157 })
158​
159 // Client-side stub for the server `delete_file` approval tool. Must be
160 // registered with `needsApproval: true` so InterruptManager hydrates the
161 // pause as `kind: 'tool-approval'` (matching schema hashes) instead of
162 // falling through to generic — otherwise Approve/Deny look up
163 // `kind === 'tool-approval'` and silently no-op.
164 const deleteFileApprovalTool = toolDefinition({
165 name: 'delete_file',
166 description: 'Delete a file (requires approval)',
167 inputSchema: z.object({
168 path: z.string(),
169 }),
170 needsApproval: true,
171 }).client()
172​
173 return [
174 readClientContextTool,
175 showNotificationTool,
176 displayChartTool,
177 failClientTool,
178 deleteFileApprovalTool,
179 ]
181​
182function createHistoryFixtureMessages(historyFixture?: string) {
183 if (historyFixture !== 'server-tool-result') {
184 return []
185 }
186​
187 const modelMessages: Array<ModelMessage> = [
188 {
189 role: 'assistant',
190 content: 'Let me check the weather.',
191 toolCalls: [
192 {
193 id: 'history-tc-1',
194 type: 'function',
195 function: {
196 name: 'getWeather',
197 arguments: '{"city":"NYC"}',
198 },
199 },
200 ],
201 },
202 {
203 role: 'tool',
204 content: '{"temp":72,"condition":"sunny"}',
205 toolCallId: 'history-tc-1',
206 },
207 ]
208​
209 return modelMessagesToUIMessages(modelMessages)
211​
212function ToolsTestPage() {
213 const {
214 testId,
215 aimockPort,
216 historyFixture,
217 scenario: initialScenario,
218 } = Route.useSearch()
219 const [scenario, setScenario] = useState(initialScenario || 'text-only')
220 const [toolEvents, setToolEvents] = useState<Array<ToolEvent>>([])
221 const [testStartTime, setTestStartTime] = useState<number | null>(null)
222 const [testComplete, setTestComplete] = useState(false)
223​
224 // Track approvals we've responded to (to avoid duplicate responses)
225 const respondedApprovals = useRef<Set<string>>(new Set())
226​
227 // Create event logger
228 const addEvent = useCallback((event: Omit<ToolEvent, 'timestamp'>) => {
229 setToolEvents((prev) => [...prev, { ...event, timestamp: Date.now() }])
230 }, [])
231​
232 // Create tracked tools (memoized since addEvent is stable)
233 const clientTools = useRef(createTrackedTools(addEvent)).current
234 // The fixture intentionally carries a `getWeather` tool call that isn't part
235 // of `clientTools`, so the generic message type can't be narrowed to the
236 // client-tool union — cast to the message type `useChat` infers from `tools`.
237 const initialMessages = useMemo(
238 () =>
239 createHistoryFixtureMessages(historyFixture) as Array<
240 UIMessage<typeof clientTools>
241 >,
242 [historyFixture],
243 )
244​
245 const { messages, sendMessage, isLoading, stop, interrupts, error } = useChat(
246 {
247 // Include scenario in ID so client is recreated when scenario changes
248 threadId: `tools-test-${scenario}-${historyFixture || 'empty'}`,
249 connection: fetchServerSentEvents('/api/tools-test'),
250 // History fixtures are untyped model-message replays; cast to the typed
251 // message shape so they don't fight the concrete `tools` tuple inference.
252 initialMessages: initialMessages,
253 forwardedProps: {
254 scenario,
255 testId,
256 aimockPort,
257 ...(scenario === 'client-server-context'
258 ? { runtimeUserId: 'client-forwarded-user-context' }
259 : {}),
260 },
261 context: clientRuntimeContext,
262 tools: clientTools,
263 onFinish: () => {
264 setTestComplete(true)
265 },
266 onCustomEvent: (eventType: string, data: unknown) => {
267 addEvent({
268 type: 'custom-event',
269 toolName: eventType,
270 details: JSON.stringify(data),
271 })
272 },
273 },
274 )
275​
276 // Track when test completes (all tool calls are complete and not loading)
277 useEffect(() => {
278 if (!isLoading && testStartTime && messages.length > 1) {
279 // Get all tool results (for server tools)
280 const resultIds = new Set(
281 messages.flatMap((msg) =>
282 msg.parts
283 .filter((p) => p.type === 'tool-result')
284 .map((p) => (p as { toolCallId: string }).toolCallId),
285 ),
286 )
287​
288 // Check if any tool calls are still pending
289 const allToolCalls = messages.flatMap((msg) =>
290 msg.parts.filter((p) => p.type === 'tool-call'),
291 )
292 const pendingCalls = allToolCalls.filter(
293 (tc) =>
294 tc.state !== 'approval-responded' &&
295 tc.output === undefined &&
296 !resultIds.has(tc.id),
297 )
298 if (pendingCalls.length === 0 && allToolCalls.length > 0) {
299 setTestComplete(true)
300 }
301 }
302 }, [isLoading, messages, testStartTime])
303​
304 const handleSendMessage = useCallback(() => {
305 // Reset test state
306 setToolEvents([])
307 setTestComplete(false)
308 setTestStartTime(Date.now())
309 respondedApprovals.current.clear()
310 sendMessage(`[${scenario}] run test`)
311 }, [sendMessage])
312​
313 // Extract tool call parts from messages for display. This harness inspects
314 // `approval` across a mixed tool set, so it uses the generic (untyped)
315 // `ToolCallPart` view — the typed per-tool parts gate `approval` behind
316 // `needsApproval`, which is exactly what we don't want to narrow on here.
317 const toolCalls: Array<ToolCallPart & { messageId: string }> =
318 messages.flatMap((msg) =>
319 msg.parts
320 .filter(
321 (p): p is Extract<typeof p, { type: 'tool-call' }> =>
322 p.type === 'tool-call',
323 )
324 .map((p) => ({
325 messageId: msg.id,
326 ...p,
327 })),
328 )
329​
330 // Extract tool result parts (for server tools)
331 const toolResultIds = new Set(
332 messages.flatMap((msg) =>
333 msg.parts
334 .filter((p) => p.type === 'tool-result')
335 .map((p) => (p as { toolCallId: string }).toolCallId),
336 ),
337 )
338​
339 // Extract approval requests
340 const pendingApprovals = toolCalls.filter(
341 (tc) => tc.approval?.needsApproval && tc.state === 'approval-requested',
342 )
343​
344 return (
345 <div
346 style={{
347 display: 'flex',
348 flexDirection: 'column',
349 height: '100vh',
350 padding: '20px',
351 fontFamily: 'system-ui, sans-serif',
352 color: '#e2e8f0',
353 }}
354 >
355 <h1 style={{ marginTop: 0 }}>Tool Testing Page</h1>
356​
357 {/* Scenario Selector */}
358 <div style={{ marginBottom: '20px' }}>
359 <label htmlFor="scenario-select" style={{ fontWeight: 'bold' }}>
360 Test Scenario:{' '}
361 </label>
362 <select
363 id="scenario-select"
364 value={scenario}
365 onChange={(e) => setScenario(e.target.value)}
366 style={{
367 padding: '8px',
368 fontSize: '14px',
369 backgroundColor: '#1e293b',
370 color: '#e2e8f0',
371 border: '1px solid #475569',
372 borderRadius: '4px',
373 }}
374 >
375 <optgroup label="Basic Scenarios">
376 {SCENARIO_LIST.filter((s) => s.category === 'basic').map((s) => (
377 <option key={s.id} value={s.id}>
378 {s.label}
379 </option>
380 ))}
381 </optgroup>
382 <optgroup label="Race Condition / Event Flow">
383 {SCENARIO_LIST.filter((s) => s.category === 'race').map((s) => (
384 <option key={s.id} value={s.id}>
385 {s.label}
386 </option>
387 ))}
388 </optgroup>
389 </select>
390 {testComplete && (
391 <span
392 id="test-complete-indicator"
393 style={{
394 marginLeft: '10px',
395 color: '#28a745',
396 fontWeight: 'bold',
397 }}
398 >
399 ✓ Test Complete
400 </span>
401 )}
402 </div>
403​
404 {/* Error Display */}
405 {error && (
406 <div
407 id="error-display"
408 style={{
409 padding: '10px',
410 background: 'rgba(220, 53, 69, 0.15)',
411 border: '1px solid rgba(220, 53, 69, 0.4)',
412 borderRadius: '4px',
413 marginBottom: '10px',
414 color: '#f8a4a4',
415 }}
416 >
417 Error: {error.message}
418 </div>
419 )}
420​
421 {/* Controls */}
422 <div style={{ display: 'flex', gap: '10px', marginBottom: '20px' }}>
423 <button
424 id="run-test-button"
425 onClick={handleSendMessage}
426 disabled={isLoading}
427 style={{
428 padding: '10px 20px',
429 fontSize: '14px',
430 backgroundColor: '#007bff',
431 color: 'white',
432 border: 'none',
433 borderRadius: '4px',
434 cursor: isLoading ? 'not-allowed' : 'pointer',
435 opacity: isLoading ? 0.7 : 1,
436 }}
437 >
438 Run Test
439 </button>
440 {isLoading && (
441 <button
442 id="stop-button"
443 onClick={stop}
444 style={{
445 padding: '10px 20px',
446 fontSize: '14px',
447 backgroundColor: '#dc3545',
448 color: 'white',
449 border: 'none',
450 borderRadius: '4px',
451 cursor: 'pointer',
452 }}
453 >
454 Stop
455 </button>
456 )}
457 </div>
458​
459 {/* Pending Approvals */}
460 {pendingApprovals.length > 0 && (
461 <div
462 id="approval-section"
463 style={{
464 marginBottom: '20px',
465 padding: '15px',
466 backgroundColor: 'rgba(255, 193, 7, 0.15)',
467 borderRadius: '4px',
468 border: '1px solid rgba(255, 193, 7, 0.4)',
469 }}
470 >
471 <h3 style={{ margin: '0 0 10px 0' }}>
472 Pending Approvals (
473 <span id="pending-approval-count">{pendingApprovals.length}</span>)
474 </h3>
475 {pendingApprovals.map((tc) => (
476 <div
477 key={tc.id}
478 data-approval-id={tc.approval?.id}
479 data-tool-name={tc.name}
480 className="approval-request"
481 style={{
482 display: 'flex',
483 alignItems: 'center',
484 gap: '10px',
485 marginBottom: '10px',
486 }}
487 >
488 <span>
489 <strong>{tc.name}</strong>: {JSON.stringify(tc.arguments)}
490 </span>
491 <button
492 id={`approve-${tc.id}`}
493 className="approve-button"
494 onClick={() => {
495 const approvalId = tc.approval?.id
496 if (
497 !approvalId ||
498 respondedApprovals.current.has(approvalId)
499 ) {
500 return
501 }
502 const interrupt = (
503 interrupts as ReadonlyArray<{
504 kind: string
505 id?: string
506 interruptId?: string
507 toolCallId?: string
508 status?: string
509 resolveInterrupt: (approved: boolean) => void
510 }>
511 ).find(
512 (item) =>
513 item.status === 'pending' &&
514 (item.toolCallId === tc.id ||
515 item.id === approvalId ||
516 item.interruptId === approvalId),
517 )
518 if (!interrupt) return
519 respondedApprovals.current.add(approvalId)
520 addEvent({
521 type: 'approval-granted',
522 toolName: tc.name,
523 toolCallId: tc.id,
524 })
525 interrupt.resolveInterrupt(true)
526 }}
527 style={{
528 padding: '5px 15px',
529 backgroundColor: '#28a745',
530 color: 'white',
531 border: 'none',
532 borderRadius: '4px',
533 cursor: 'pointer',
534 }}
535 >
536 Approve
537 </button>
538 <button
539 id={`deny-${tc.id}`}
540 className="deny-button"
541 onClick={() => {
542 const approvalId = tc.approval?.id
543 if (
544 !approvalId ||
545 respondedApprovals.current.has(approvalId)
546 ) {
547 return
548 }
549 const interrupt = (
550 interrupts as ReadonlyArray<{
551 kind: string
552 id?: string
553 interruptId?: string
554 toolCallId?: string
555 status?: string
556 resolveInterrupt: (approved: boolean) => void
557 }>
558 ).find(
559 (item) =>
560 item.status === 'pending' &&
561 (item.toolCallId === tc.id ||
562 item.id === approvalId ||
563 item.interruptId === approvalId),
564 )
565 if (!interrupt) return
566 respondedApprovals.current.add(approvalId)
567 addEvent({
568 type: 'approval-denied',
569 toolName: tc.name,
570 toolCallId: tc.id,
571 })
572 interrupt.resolveInterrupt(false)
573 }}
574 style={{
575 padding: '5px 15px',
576 backgroundColor: '#dc3545',
577 color: 'white',
578 border: 'none',
579 borderRadius: '4px',
580 cursor: 'pointer',
581 }}
582 >
583 Deny
584 </button>
585 </div>
586 ))}
587 </div>
588 )}
589​
590 {/* Event Log - tracks execution flow for testing */}
591 <div
592 id="event-log-section"
593 style={{
594 marginBottom: '20px',
595 padding: '15px',
596 backgroundColor: 'rgba(23, 162, 184, 0.1)',
597 borderRadius: '4px',
598 border: '1px solid rgba(23, 162, 184, 0.3)',
599 maxHeight: '150px',
600 overflow: 'auto',
601 }}
602 >
603 <h3 style={{ margin: '0 0 10px 0' }}>
604 Event Log (<span id="event-count">{toolEvents.length}</span>)
605 </h3>
606 {toolEvents.length === 0 ? (
607 <p style={{ color: '#8899aa', margin: 0 }}>No events yet</p>
608 ) : (
609 <div id="event-log">
610 {toolEvents.map((event, i) => (
611 <div
612 key={i}
613 className={`event-entry event-${event.type}`}
614 data-event-type={event.type}
615 data-tool-name={event.toolName}
616 style={{
617 fontFamily: 'monospace',
618 fontSize: '11px',
619 marginBottom: '2px',
620 color:
621 event.type === 'execution-complete' ||
622 event.type === 'approval-granted'
623 ? '#6ee7b7'
624 : event.type === 'error' ||
625 event.type === 'approval-denied'
626 ? '#fca5a5'
627 : '#67e8f9',
628 }}
629 >
630 [
631 {new Date(event.timestamp)
632 .toISOString()
633 .split('T')[1]
634 ?.slice(0, 12)}
635 ] <strong>{event.type}</strong>: {event.toolName}
636 {event.details ? ` - ${event.details}` : ''}
637 </div>
638 ))}
639 </div>
640 )}
641 </div>
642​
643 {/* Tool Calls Display */}
644 <div
645 id="tool-calls-section"
646 style={{
647 marginBottom: '20px',
648 padding: '15px',
649 backgroundColor: 'rgba(100, 116, 139, 0.1)',
650 borderRadius: '4px',
651 border: '1px solid rgba(100, 116, 139, 0.3)',
652 maxHeight: '200px',
653 overflow: 'auto',
654 }}
655 >
656 <h3 style={{ margin: '0 0 10px 0' }}>Tool Calls</h3>
657 {toolCalls.length === 0 ? (
658 <p style={{ color: '#8899aa' }}>No tool calls yet</p>
659 ) : (
660 <table style={{ width: '100%', fontSize: '12px' }}>
661 <thead>
662 <tr>
663 <th style={{ textAlign: 'left' }}>Tool</th>
664 <th style={{ textAlign: 'left' }}>State</th>
665 <th style={{ textAlign: 'left' }}>Arguments</th>
666 <th style={{ textAlign: 'left' }}>Output</th>
667 </tr>
668 </thead>
669 <tbody id="tool-calls-table">
670 {toolCalls.map((tc) => (
671 <tr key={tc.id} data-tool-id={tc.id} data-tool-state={tc.state}>
672 <td>{tc.name}</td>
673 <td>
674 <span
675 style={{
676 padding: '2px 6px',
677 borderRadius: '3px',
678 backgroundColor:
679 tc.output !== undefined ||
680 tc.state === 'approval-responded'
681 ? '#28a745'
682 : tc.state === 'input-streaming'
683 ? '#ffc107'
684 : tc.state === 'approval-requested'
685 ? '#17a2b8'
686 : '#6c757d',
687 color: 'white',
688 fontSize: '11px',
689 }}
690 >
691 {tc.state}
692 </span>
693 </td>
694 <td style={{ fontFamily: 'monospace' }}>
695 {typeof tc.arguments === 'string'
696 ? tc.arguments
697 : JSON.stringify(tc.arguments)}
698 </td>
699 <td style={{ fontFamily: 'monospace' }}>
700 {tc.output ? JSON.stringify(tc.output) : '-'}
701 </td>
702 </tr>
703 ))}
704 </tbody>
705 </table>
706 )}
707 </div>
708​
709 {/* Messages JSON Display */}
710 <div
711 id="messages-json"
712 style={{
713 flex: 1,
714 overflow: 'auto',
715 padding: '10px',
716 backgroundColor: 'rgba(15, 23, 42, 0.6)',
717 border: '1px solid rgba(100, 116, 139, 0.3)',
718 borderRadius: '4px',
719 fontFamily: 'monospace',
720 fontSize: '12px',
721 color: '#94a3b8',
722 }}
723 >
724 <pre
725 id="messages-json-content"
726 style={{ margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}
727 >
728 {JSON.stringify(messages, null, 2)}
729 </pre>
730 </div>
731​
732 {/* Test metadata for assertions */}
733 <div
734 id="test-metadata"
735 style={{ display: 'none' }}
736 data-scenario={scenario}
737 data-history-fixture={historyFixture || ''}
738 data-is-loading={isLoading.toString()}
739 data-test-complete={testComplete.toString()}
740 data-tool-call-count={toolCalls.length}
741 data-pending-approval-count={pendingApprovals.length}
742 data-complete-tool-count={
743 toolCalls.filter(
744 (tc) =>
745 tc.state === 'approval-responded' ||
746 tc.output !== undefined ||
747 toolResultIds.has(tc.id),
748 ).length
749 }
750 data-event-count={toolEvents.length}
751 data-execution-start-count={
752 toolEvents.filter((e) => e.type === 'execution-start').length
753 }
754 data-execution-complete-count={
755 toolEvents.filter((e) => e.type === 'execution-complete').length
756 }
757 data-approval-granted-count={
758 toolEvents.filter((e) => e.type === 'approval-granted').length
759 }
760 data-approval-denied-count={
761 toolEvents.filter((e) => e.type === 'approval-denied').length
762 }
763 data-custom-event-count={
764 toolEvents.filter((e) => e.type === 'custom-event').length
765 }
766 data-has-error={(!!error).toString()}
767 data-error-message={error?.message || ''}
768 data-error-raw-event={
769 error && 'rawEvent' in error
770 ? JSON.stringify((error as { rawEvent?: unknown }).rawEvent)
771 : ''
772 }
773 />
774​
775 {/* Event log as JSON for easy parsing in tests */}
776 <script
777 id="event-log-json"
778 type="application/json"
779 dangerouslySetInnerHTML={{ __html: JSON.stringify(toolEvents) }}
780 />
781​
782 {/* Tool calls as JSON for easy parsing in tests */}
783 <script
784 id="tool-calls-json"
785 type="application/json"
786 dangerouslySetInnerHTML={{
787 __html: JSON.stringify(
788 toolCalls.map((tc) => ({
789 id: tc.id,
790 name: tc.name,
791 state: tc.state,
792 hasOutput: !!tc.output,
793 })),
794 ),
795 }}
796 />
797 </div>
798 )
800​
801export const Route = createFileRoute('/tools-test')({
802 component: ToolsTestPage,
803 validateSearch: (search: Record<string, unknown>) => {
804 return {
805 testId: typeof search.testId === 'string' ? search.testId : undefined,
806 aimockPort: parseAimockPort(search.aimockPort),
807 historyFixture:
808 typeof search.historyFixture === 'string'
809 ? search.historyFixture
810 : undefined,
811 scenario:
812 typeof search.scenario === 'string' ? search.scenario : undefined,
813 }
814 },
815})