Repository navigation
Expand file tree
/
Copy pathApp.tsx
More file actions
477 lines (446 loc) · 14.8 KB
/
Copy pathApp.tsx
File metadata and controls
477 lines (446 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {
A2UIClient,
A2UIRenderer,
type TimelineItem,
themeStyleSheet,
} from '@googlemaps/a2ui/lit';
import {useEffect, useRef, useState} from 'react';
import './App.css';
// --- Configuration ---
const DEFAULT_USE_STREAMING = true;
type AgentType = 'mcp' | 'vertex' | 'template';
interface AgentOption {
readonly id: AgentType;
readonly label: string;
readonly prefix: string;
}
const AGENT_OPTIONS: readonly AgentOption[] = [
{id: 'mcp', label: 'Grounding Lite (MCP)', prefix: ''},
{
id: 'vertex',
label: 'Grounding with Google Maps (Vertex)',
prefix: '[GROUNDING] ',
},
{id: 'template', label: 'Template Agent', prefix: '[TEMPLATE] '},
];
const DEFAULT_AGENT_TYPE: AgentType = 'mcp';
/**
* Main Application component that demonstrates A2UI integration in a React environment.
* It manages a chat interface with a timeline of text messages and A2UI interactive surfaces.
*/
function App() {
// --- UI State ---
const [isChatOpen, setIsChatOpen] = useState(true);
const [useStreaming, setUseStreaming] = useState(DEFAULT_USE_STREAMING);
const [selectedAgentType, setSelectedAgentType] =
useState<AgentType>(DEFAULT_AGENT_TYPE);
const [timeline, setTimeline] = useState<TimelineItem[]>([]);
const [input, setInput] = useState('');
const [isRequesting, setIsRequesting] = useState(false);
const [importJson, setImportJson] = useState('');
const importDialogRef = useRef<HTMLDialogElement>(null);
const [lastResponseJson, setLastResponseJson] = useState('');
// --- A2UI Integration Refs ---
// A2UIClient handles communication with the A2A agent
const clientRef = useRef(new A2UIClient());
// A2UIRenderer manages the local state of A2UI surfaces and message processing
const rendererRef = useRef(new A2UIRenderer());
// Handle scrolling properly.
const messagesEndRef = useRef<HTMLDivElement>(null);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({behavior: 'smooth'});
};
useEffect(() => {
scrollToBottom();
}, [timeline]);
useEffect(() => {
if (!document.adoptedStyleSheets.includes(themeStyleSheet)) {
document.adoptedStyleSheets = [
...document.adoptedStyleSheets,
themeStyleSheet,
];
}
}, []);
const handleImport = () => {
try {
const messages = JSON.parse(importJson);
rendererRef.current = new A2UIRenderer();
rendererRef.current.processResponse(
messages.map((msg: any) => ({type: 'a2ui', message: msg})),
);
setTimeline([...rendererRef.current.timeline]);
importDialogRef.current?.close();
setImportJson('');
} catch (e) {
alert('Failed to parse JSON: ' + e);
}
};
/**
* Handles sending a text message from the user.
* Updates the UI timeline and processes the agent's response.
*/
const handleSend = async () => {
if (!input.trim() || isRequesting) return;
const messageText = input.trim();
const selectedAgent = AGENT_OPTIONS.find(
(option) => option.id === selectedAgentType,
);
const serverText = `${selectedAgent?.prefix ?? ''}${messageText}`;
setInput('');
setIsRequesting(true);
// 1. Add the user's message to the local renderer's timeline
rendererRef.current.addUserMessage(messageText);
setTimeline([...rendererRef.current.timeline]);
try {
if (useStreaming) {
const streamedMessages: any[] = [];
for await (const chunk of clientRef.current.sendStream(serverText)) {
rendererRef.current.processResponse([chunk as any]);
if (chunk.type === 'a2ui') {
streamedMessages.push(chunk.message);
setLastResponseJson(JSON.stringify(streamedMessages, null, 2));
}
setTimeline([...rendererRef.current.timeline]);
}
} else {
// 2. Send the message to the A2A agent via A2UIClient
const response = await clientRef.current.send(serverText);
// 3. Process the response (which may contain text and/or A2UI data)
rendererRef.current.processResponse(response);
// Update last response JSON
const uiMessages = response
.filter((p: any) => p.type === 'a2ui')
.map((p: any) => p.message);
if (uiMessages.length > 0) {
setLastResponseJson(JSON.stringify(uiMessages, null, 2));
}
// 4. Synchronize the React state with the renderer's updated timeline
setTimeline([...rendererRef.current.timeline]);
}
} catch (error) {
console.error('Failed to send message:', error);
rendererRef.current.processResponse([
{
type: 'text',
text: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`,
},
]);
setTimeline([...rendererRef.current.timeline]);
} finally {
setIsRequesting(false);
}
};
return (
<div className="app-container">
{/* --- Main Content Panel --- */}
<main className="main-panel">
{!isChatOpen && (
<button
className="toggle-chat-btn"
onClick={() => setIsChatOpen(true)}>
Open Chat
</button>
)}
<div className="main-panel-content">
<h1>Main content</h1>
</div>
</main>
{/* --- Side Chat Panel --- */}
<aside className={`chat-panel ${isChatOpen ? 'open' : 'closed'}`}>
<div className="chat-header">
<h2>Chat</h2>
<label className="streaming-toggle">
<input
type="checkbox"
checked={useStreaming}
onChange={(e) => setUseStreaming(e.target.checked)}
/>
Streaming
</label>
<button
className="close-chat-btn"
onClick={() => setIsChatOpen(false)}>
×
</button>
</div>
{/* --- Message Timeline --- */}
<div className="chat-messages">
<maui-providers>
{timeline.length === 0 && (
<p style={{opacity: 0.5, textAlign: 'center', marginTop: '50px'}}>
No messages yet.
</p>
)}
{timeline.map((item, idx) => {
if (item.type === 'user') {
return (
<div key={idx} className="user-message">
{item.text}
</div>
);
} else if (item.type === 'action') {
return (
<div key={idx} className="action-message">
<strong>A2UI Action: {item.action}</strong>
<pre>{item.text}</pre>
</div>
);
} else if (item.type === 'text') {
return (
<div key={idx} className="bot-message">
{item.text}
</div>
);
} else if (item.type === 'surface') {
// Render an A2UI Surface containing multiple UI components
const surface = rendererRef.current.getSurface(item.surfaceId);
if (!surface) return null;
return (
<div key={item.surfaceId} className="surface-message">
{/* @ts-ignore */}
<a2ui-surface
surface={surface}
></a2ui-surface>
</div>
);
}
return null;
})}
{isRequesting && <div className="loading-spinner">Thinking...</div>}
<div ref={messagesEndRef} />
</maui-providers>
</div>
{/* --- Chat Input Area --- */}
<div className="chat-input-area">
<div
className="agent-selector"
role="radiogroup"
aria-label="Agent type">
{AGENT_OPTIONS.map((option) => (
<label key={option.id} className="agent-option">
<input
type="radio"
name="agent-type"
value={option.id}
checked={selectedAgentType === option.id}
onChange={() => setSelectedAgentType(option.id)}
disabled={isRequesting}
/>
<span>{option.label}</span>
</label>
))}
</div>
<textarea
className="chat-textarea"
placeholder="Type a message..."
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
}}
disabled={isRequesting}></textarea>
<div className="chat-actions">
{lastResponseJson && <ResponseViewer json={lastResponseJson} />}
<button
className="import-btn-input"
onClick={() => importDialogRef.current?.showModal()}
style={{
background: 'transparent',
color: 'var(--accent, #1a73e8)',
border: '1px solid var(--accent, #1a73e8)',
padding: '10px 24px',
borderRadius: '9999px',
fontWeight: 500,
cursor: 'pointer',
marginRight: '8px',
}}>
Import JSON
</button>
<button
className="send-button"
onClick={handleSend}
disabled={isRequesting || !input.trim()}>
{isRequesting ? '...' : 'Send'}
</button>
</div>
</div>
</aside>
<dialog
ref={importDialogRef}
onClick={(e) => {
if (e.target === importDialogRef.current)
importDialogRef.current.close();
}}
style={{
border: 'none',
borderRadius: '16px',
padding: '0',
width: '90%',
maxWidth: '600px',
}}>
<div
className="dialog-content"
style={{
background: 'white',
padding: '24px',
borderRadius: '16px',
display: 'flex',
flexDirection: 'column',
gap: '16px',
}}>
<h2 style={{margin: 0, fontSize: '1.25rem', fontWeight: 600}}>
Import A2UI JSON
</h2>
<textarea
placeholder='[ { "surfaceUpdate": { ... } }, ... ]'
value={importJson}
onChange={(e) => setImportJson(e.target.value)}
style={{
width: '100%',
minHeight: '200px',
fontFamily: 'monospace',
boxSizing: 'border-box',
padding: '12px',
}}></textarea>
<div
className="dialog-footer"
style={{
display: 'flex',
justifyContent: 'flex-end',
gap: '12px',
marginTop: '12px',
}}>
<button
className="cancel-btn"
onClick={() => importDialogRef.current?.close()}>
Cancel
</button>
<button
className="render-btn"
onClick={handleImport}
style={{
background: 'var(--p-40, #1a73e8)',
color: 'white',
border: 'none',
padding: '8px 16px',
borderRadius: '4px',
cursor: 'pointer',
}}>
Render A2UI
</button>
</div>
</div>
</dialog>
</div>
);
}
function ResponseViewer({json}: {json: string}) {
const [copied, setCopied] = useState(false);
const dialogRef = useRef<HTMLDialogElement>(null);
const handleCopy = () => {
navigator.clipboard.writeText(json);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
return (
<>
<button
className="view-response-btn"
onClick={() => dialogRef.current?.showModal()}
style={{
background: 'transparent',
color: 'var(--accent, #1a73e8)',
border: '1px solid var(--accent, #1a73e8)',
padding: '10px 24px',
borderRadius: '9999px',
fontWeight: 500,
cursor: 'pointer',
marginRight: '8px',
}}>
View Last Response
</button>
<dialog
ref={dialogRef}
onClick={(e) => {
if (e.target === dialogRef.current) dialogRef.current.close();
}}
style={{
border: 'none',
borderRadius: '16px',
padding: '0',
width: '90%',
maxWidth: '600px',
}}>
<div
className="dialog-content"
style={{
background: 'white',
padding: '24px',
borderRadius: '16px',
display: 'flex',
flexDirection: 'column',
gap: '16px',
}}>
<h2 style={{margin: 0, fontSize: '1.25rem', fontWeight: 600}}>
Last A2UI Response
</h2>
<pre
style={{
background: 'rgba(0,0,0,0.05)',
padding: '12px',
borderRadius: '8px',
overflowX: 'auto',
maxHeight: '300px',
whiteSpace: 'pre-wrap',
}}>
{json || 'No response yet.'}
</pre>
<div
className="dialog-footer"
style={{display: 'flex', justifyContent: 'flex-end', gap: '12px'}}>
<button
onClick={() => dialogRef.current?.close()}
style={{
background: 'var(--n-90, #e0e0e0)',
border: 'none',
padding: '8px 16px',
borderRadius: '4px',
cursor: 'pointer',
}}>
Close
</button>
<button
onClick={handleCopy}
style={{
background: copied ? '#137333' : 'var(--p-40, #1a73e8)',
color: 'white',
border: 'none',
padding: '8px 16px',
borderRadius: '4px',
cursor: 'pointer',
}}>
{copied ? 'Copied!' : 'Copy JSON'}
</button>
</div>
</div>
</dialog>
</>
);
}
export default App;