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

capability-demo.tsx

228 lines8.2 KB

1import { useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { Send, Sparkles, Square } from 'lucide-react'
4import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
5import type { UIMessage } from '@tanstack/ai-react'
6​
7interface SessionConfig {
8 persona: string
9 provideCapability: boolean
10 /** Bumped on every Apply so the chat surface remounts with a fresh session. */
11 seq: number
13​
14function Messages({ messages }: { messages: ReadonlyArray<UIMessage> }) {
15 const visible = messages.filter((m) =>
16 m.parts.some((p) => p.type === 'text' && p.content.trim()),
17 )
18​
19 if (!visible.length) {
20 return (
21 <div className="flex-1 overflow-y-auto px-4 py-8">
22 <p className="text-center text-sm text-gray-400">
23 Send a message — the assistant should answer in the persona supplied
24 by the capability.
25 </p>
26 </div>
27 )
28 }
29​
30 return (
31 <div className="flex-1 overflow-y-auto px-4 py-4">
32 {visible.map((message) => (
33 <div
34 key={message.id}
35 className={`mb-2 rounded-lg p-4 ${
36 message.role === 'assistant'
37 ? 'bg-linear-to-r from-cyan-500/5 to-blue-600/5'
38 : 'bg-transparent'
39 }`}
40 >
41 <div className="flex items-start gap-4">
42 <div
43 className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-sm font-medium text-white ${
44 message.role === 'assistant'
45 ? 'bg-linear-to-r from-cyan-500 to-blue-600'
46 : 'bg-gray-700'
47 }`}
48 >
49 {message.role === 'assistant' ? 'AI' : 'U'}
50 </div>
51 <div className="min-w-0 flex-1">
52 {message.parts.map((part, index) =>
53 part.type === 'text' && part.content ? (
54 <p
55 key={`text-${index}`}
56 className="whitespace-pre-wrap text-white"
57 >
58 {part.content}
59 </p>
60 ) : null,
61 )}
62 </div>
63 </div>
64 </div>
65 ))}
66 </div>
67 )
69​
70function ChatSurface({ config }: { config: SessionConfig }) {
71 const { messages, sendMessage, isLoading, error, stop } = useChat({
72 threadId: `capability-demo-${config.seq}`,
73 connection: fetchServerSentEvents('/api/capability-demo'),
74 // Forwarded to the route as `forwardedProps`: the provider middleware
75 // provides `capabilityValue`; `provideCapability=false` omits the provider
76 // so chat() throws the capability validation error.
77 forwardedProps: {
78 capabilityValue: config.persona,
79 provideCapability: config.provideCapability,
80 },
81 })
82​
83 const [input, setInput] = useState('')
84​
85 const handleSend = () => {
86 if (!input.trim()) return
87 sendMessage(input.trim())
88 setInput('')
89 }
90​
91 return (
92 <div className="flex min-h-0 flex-1 flex-col">
93 <Messages messages={messages} />
94​
95 {error && (
96 <div className="mx-4 mt-2 rounded-lg border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-400">
97 <span className="font-semibold">chat() error:</span> {error.message}
98 </div>
99 )}
100​
101 <div className="border-t border-cyan-500/10 bg-gray-900/80 backdrop-blur-sm">
102 <div className="w-full space-y-2 px-4 py-3">
103 {isLoading && (
104 <div className="flex items-center justify-center">
105 <button
106 onClick={stop}
107 className="flex items-center gap-2 rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700"
108 >
109 <Square className="h-4 w-4 fill-current" />
110 Stop
111 </button>
112 </div>
113 )}
114 <div className="relative flex items-end gap-2">
115 <textarea
116 value={input}
117 onChange={(e) => setInput(e.target.value)}
118 placeholder="Say hello..."
119 className="w-full resize-none overflow-hidden rounded-lg border border-cyan-500/20 bg-gray-800/50 py-3 pl-4 pr-12 text-sm text-white placeholder-gray-400 shadow-lg focus:border-transparent focus:outline-none focus:ring-2 focus:ring-cyan-500/50"
120 rows={1}
121 style={{ minHeight: '44px', maxHeight: '200px' }}
122 disabled={isLoading}
123 onKeyDown={(e) => {
124 if (e.key === 'Enter' && !e.shiftKey && input.trim()) {
125 e.preventDefault()
126 handleSend()
127 }
128 }}
129 />
130 <button
131 onClick={handleSend}
132 disabled={!input.trim() || isLoading}
133 className="absolute right-2 top-1/2 -translate-y-1/2 p-2 text-cyan-500 transition-colors hover:text-cyan-400 disabled:text-gray-500 focus:outline-none"
134 >
135 <Send className="h-4 w-4" />
136 </button>
137 </div>
138 </div>
139 </div>
140 </div>
141 )
143​
144function CapabilityDemoPage() {
145 const [draftPersona, setDraftPersona] = useState('a cheerful pirate captain')
146 const [draftProvide, setDraftProvide] = useState(true)
147 const [config, setConfig] = useState<SessionConfig>({
148 persona: 'a cheerful pirate captain',
149 provideCapability: true,
150 seq: 0,
151 })
152​
153 const apply = () => {
154 setConfig((prev) => ({
155 persona: draftPersona,
156 provideCapability: draftProvide,
157 seq: prev.seq + 1,
158 }))
159 }
160​
161 const dirty =
162 draftPersona !== config.persona || draftProvide !== config.provideCapability
163​
164 return (
165 <div className="flex h-[calc(100vh-72px)] flex-col bg-gray-900">
166 <div className="shrink-0 border-b border-cyan-500/20 bg-gray-800 px-4 py-3">
167 <div className="mb-2 flex items-center gap-2">
168 <Sparkles className="h-4 w-4 text-cyan-400" />
169 <h2 className="text-sm font-semibold text-white">
170 Middleware Capabilities
171 </h2>
172 </div>
173 <p className="mb-3 text-xs text-gray-400">
174 A <span className="text-cyan-300">provider</span> middleware supplies
175 a persona capability in <code className="text-gray-300">setup()</code>
176 ; a <span className="text-cyan-300">consumer</span> middleware reads
177 it in <code className="text-gray-300">onConfig()</code> and injects a
178 system prompt. With the capability provided, the middleware is wired
179 through the type-safe{' '}
180 <code className="text-gray-300">
181 createChatMiddleware().use().build()
182 </code>{' '}
183 builder. Uncheck “Provide capability” to omit the provider and watch{' '}
184 <code className="text-gray-300">chat()</code> throw the runtime
185 validation error. Requires{' '}
186 <code className="text-gray-300">OPENAI_API_KEY</code>.
187 </p>
188​
189 <div className="flex flex-wrap items-end gap-3">
190 <label className="flex flex-col gap-1">
191 <span className="text-xs uppercase tracking-wide text-gray-500">
192 Persona (capability value)
193 </span>
194 <input
195 type="text"
196 value={draftPersona}
197 onChange={(e) => setDraftPersona(e.target.value)}
198 className="w-72 rounded-lg border border-gray-600 bg-gray-700/50 px-3 py-2 text-sm text-white focus:border-cyan-500/50 focus:outline-none"
199 />
200 </label>
201​
202 <label className="flex cursor-pointer items-center gap-2 rounded-lg border border-gray-600 bg-gray-700/50 px-3 py-2 text-sm text-gray-200">
203 <input
204 type="checkbox"
205 checked={draftProvide}
206 onChange={(e) => setDraftProvide(e.target.checked)}
207 />
208 <span>Provide capability</span>
209 </label>
210​
211 <button
212 onClick={apply}
213 disabled={!dirty}
214 className="rounded-lg bg-cyan-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-cyan-700 disabled:bg-gray-600 disabled:text-gray-400"
215 >
216 {config.seq === 0 ? 'Start session' : 'Apply (new session)'}
217 </button>
218 </div>
219 </div>
220​
221 <ChatSurface key={config.seq} config={config} />
222 </div>
223 )
225​
226export const Route = createFileRoute('/capability-demo')({
227 component: CapabilityDemoPage,
228})