Open History to see the last commit
1import { useEffect, useRef, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import {
4 fetchServerSentEvents,
5 useChat,
6 type GenericInterrupt,
7 type UIMessage,
8} from '@tanstack/ai-react'
9import { computerSafetyCheck } from '@tanstack/ai-computer-use'
10
11const TASK = `You are on the TanStack home page. Find the TanStack AI documentation page about computer use.
12Use the screenshots. Click, type, and scroll only on what you can see. Do not type a URL from memory.
13When the page is the computer use docs, say the page title and stop.`
14
15type Part = UIMessage['parts'][number]
16
17/** The screenshots in one tool result, as `<img>` sources. */
18function screenshots(part: Part) {
19 if (part.type !== 'tool-result' || typeof part.content === 'string') return []
20 return part.content.flatMap((content) => {
21 if (content.type !== 'image') return []
22 const { source } = content
23 if (source.type === 'data') {
24 return [`data:${source.mimeType};base64,${source.value}`]
25 }
26 return source.type === 'url' ? [source.value] : []
27 })
28}
29
30function Messages({ messages }: { messages: ReadonlyArray<UIMessage> }) {
31 const containerRef = useRef<HTMLDivElement>(null)
32
33 useEffect(() => {
34 if (containerRef.current) {
35 containerRef.current.scrollTop = containerRef.current.scrollHeight
36 }
37 }, [messages])
38
39 if (!messages.length) {
40 return (
41 <div className="flex-1 overflow-y-auto px-4 py-8">
42 <div className="mx-auto max-w-2xl text-center">
43 <h2 className="mb-2 text-xl font-semibold text-white">
44 Computer Use
45 </h2>
46 <p className="text-sm text-gray-400">
47 Click Send. A Chromium window opens on tanstack.com, and the model
48 looks for the computer use docs. Each screenshot shows here.
49 </p>
50 </div>
51 </div>
52 )
53 }
54
55 return (
56 <div ref={containerRef} className="flex-1 overflow-y-auto px-4 py-4">
57 {messages.map((message) => (
58 <div
59 key={message.id}
60 className={`mb-2 rounded-lg p-4 ${
61 message.role === 'assistant'
62 ? 'bg-linear-to-r from-orange-500/5 to-red-600/5'
63 : 'bg-transparent'
64 }`}
65 >
66 {message.parts.map((part, index) => {
67 if (part.type === 'text' && part.content) {
68 return (
69 <div key={index} className="whitespace-pre-wrap text-white">
70 {part.content}
71 </div>
72 )
73 }
74 return screenshots(part).map((src) => (
75 <img
76 key={`${index}-${src.slice(-16)}`}
77 src={src}
78 alt="What the model sees"
79 className="my-2 max-w-xl rounded border border-gray-700"
80 />
81 ))
82 })}
83 </div>
84 ))}
85 </div>
86 )
87}
88
89/** OpenAI can mark an action as risky. A person approves it before it runs. */
90function SafetyCheckCard({
91 interrupt,
92}: {
93 interrupt: GenericInterrupt<typeof computerSafetyCheck>
94}) {
95 const checks = interrupt.payload?.checks ?? []
96 return (
97 <div className="mx-4 mt-2 rounded-lg border border-yellow-500/30 bg-yellow-500/10 p-3 text-sm text-yellow-100">
98 <p className="font-medium">Approve this computer action?</p>
99 <ul className="my-2 list-disc pl-5">
100 {checks.map((check) => (
101 <li key={check.id}>{check.message ?? check.code ?? check.id}</li>
102 ))}
103 </ul>
104 <pre className="mb-2 overflow-x-auto text-xs">
105 {JSON.stringify(interrupt.payload?.action, null, 2)}
106 </pre>
107 <div className="flex gap-2">
108 <button
109 type="button"
110 onClick={() => interrupt.resolveInterrupt({ approved: true })}
111 className="rounded bg-orange-500 px-3 py-1 text-white"
112 >
113 Approve
114 </button>
115 <button
116 type="button"
117 onClick={() => interrupt.resolveInterrupt({ approved: false })}
118 className="rounded bg-gray-700 px-3 py-1 text-white"
119 >
120 Decline
121 </button>
122 </div>
123 </div>
124 )
125}
126
127function ChatPage() {
128 const [input, setInput] = useState(TASK)
129 const { messages, sendMessage, isLoading, error, stop, interrupts } = useChat(
130 {
131 connection: fetchServerSentEvents('/api/chat'),
132 threadId: 'computer-use',
133 interrupts: [computerSafetyCheck],
134 },
135 )
136
137 const handleSendMessage = () => {
138 if (!input.trim()) return
139 sendMessage(input.trim())
140 setInput('')
141 }
142
143 return (
144 <div className="flex h-screen bg-gray-900">
145 <div className="flex w-full flex-col">
146 <Messages messages={messages} />
147
148 {interrupts.map((interrupt) => {
149 if (interrupt.kind !== 'generic') return null
150 if (!('definitionId' in interrupt)) return null
151 if (interrupt.definitionId !== computerSafetyCheck.id) return null
152 return <SafetyCheckCard key={interrupt.id} interrupt={interrupt} />
153 })}
154
155 {error ? (
156 <div className="mx-4 mt-2 rounded-lg border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-400">
157 {error.message}
158 </div>
159 ) : null}
160
161 <div className="border-t border-orange-500/10 bg-gray-900/80">
162 <div className="w-full px-4 py-3">
163 {isLoading ? (
164 <div className="mb-3 flex items-center justify-center">
165 <button
166 type="button"
167 onClick={stop}
168 className="rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700"
169 >
170 Stop
171 </button>
172 </div>
173 ) : null}
174 <div className="flex items-end gap-2">
175 <textarea
176 value={input}
177 onChange={(event) => setInput(event.target.value)}
178 placeholder="Tell the model what to do on the page..."
179 className="w-full resize-none rounded-lg border border-orange-500/20 bg-gray-800/50 px-4 py-3 text-sm text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-orange-500/50"
180 rows={3}
181 disabled={isLoading}
182 />
183 <button
184 type="button"
185 onClick={handleSendMessage}
186 disabled={!input.trim() || isLoading}
187 className="rounded-lg bg-orange-500 px-4 py-3 text-sm font-medium text-white disabled:opacity-50"
188 >
189 Send
190 </button>
191 </div>
192 </div>
193 </div>
194 </div>
195 </div>
196 )
197}
198
199export const Route = createFileRoute('/')({
200 component: ChatPage,
201})