oneie 3.6.35 → 3.6.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,559 @@
1
+ ---
2
+ title: Generative Ui Patterns
3
+ dimension: knowledge
4
+ category: patterns
5
+ tags: ai, generative-ui, react, components, recharts
6
+ related_dimensions: things, knowledge
7
+ scope: global
8
+ created: 2025-11-10
9
+ updated: 2025-11-10
10
+ version: 1.0.0
11
+ ---
12
+
13
+ # Generative UI Patterns
14
+
15
+ **Version:** 1.0.0
16
+ **Purpose:** Best practices for dynamic UI component generation by AI agents
17
+ **Stack:** React 19 + shadcn/ui + Recharts + AG-UI Protocol
18
+
19
+ ## Overview
20
+
21
+ **Generative UI** allows AI agents to dynamically create UI components based on data. Instead of returning HTML strings (security risk), agents return structured component specifications that the frontend renders safely.
22
+
23
+ **Traditional Approach (Bad):**
24
+ ```typescript
25
+ // Security risk: XSS vulnerability
26
+ return "<div class='chart'>...</div>";
27
+ ```
28
+
29
+ **Generative UI Approach (Good):**
30
+ ```typescript
31
+ // Type-safe, secure, flexible
32
+ return {
33
+ component: 'chart',
34
+ data: {
35
+ chartType: 'line',
36
+ labels: ['Jan', 'Feb', 'Mar'],
37
+ datasets: [{ label: 'Revenue', data: [10, 20, 30] }]
38
+ }
39
+ };
40
+ ```
41
+
42
+ ## Pattern 1: DynamicChart (Recharts)
43
+
44
+ ### Implementation
45
+
46
+ ```tsx
47
+ import { LineChart, BarChart, PieChart, Line, Bar, Pie, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts';
48
+ import { Card, CardHeader, CardTitle, CardDescription, CardContent } from '@/components/ui/card';
49
+ import type { ChartComponentData } from '@/convex/protocols/agent-ui';
50
+
51
+ export function DynamicChart({ data, layout }: {
52
+ data: ChartComponentData['data'];
53
+ layout?: any
54
+ }) {
55
+ // Transform data for Recharts
56
+ const chartData = data.labels.map((label, i) => ({
57
+ name: label,
58
+ ...data.datasets.reduce((acc, dataset) => ({
59
+ ...acc,
60
+ [dataset.label]: dataset.data[i]
61
+ }), {})
62
+ }));
63
+
64
+ const renderChart = () => {
65
+ switch (data.chartType) {
66
+ case 'line':
67
+ return (
68
+ <LineChart data={chartData} width={600} height={300}>
69
+ <CartesianGrid strokeDasharray="3 3" />
70
+ <XAxis dataKey="name" />
71
+ <YAxis />
72
+ <Tooltip />
73
+ <Legend />
74
+ {data.datasets.map((dataset, i) => (
75
+ <Line
76
+ key={i}
77
+ type="monotone"
78
+ dataKey={dataset.label}
79
+ stroke={dataset.color || `hsl(var(--chart-${i + 1}))`}
80
+ fill={dataset.fill ? dataset.color : undefined}
81
+ />
82
+ ))}
83
+ </LineChart>
84
+ );
85
+
86
+ case 'bar':
87
+ return (
88
+ <BarChart data={chartData} width={600} height={300}>
89
+ <CartesianGrid strokeDasharray="3 3" />
90
+ <XAxis dataKey="name" />
91
+ <YAxis />
92
+ <Tooltip />
93
+ <Legend />
94
+ {data.datasets.map((dataset, i) => (
95
+ <Bar
96
+ key={i}
97
+ dataKey={dataset.label}
98
+ fill={dataset.color || `hsl(var(--chart-${i + 1}))`}
99
+ />
100
+ ))}
101
+ </BarChart>
102
+ );
103
+
104
+ case 'pie':
105
+ return (
106
+ <PieChart width={600} height={300}>
107
+ <Pie
108
+ data={chartData}
109
+ dataKey={data.datasets[0]?.label || 'value'}
110
+ nameKey="name"
111
+ cx="50%"
112
+ cy="50%"
113
+ outerRadius={100}
114
+ fill={`hsl(var(--chart-1))`}
115
+ label
116
+ />
117
+ <Tooltip />
118
+ </PieChart>
119
+ );
120
+
121
+ default:
122
+ return <p>Unsupported chart type: {data.chartType}</p>;
123
+ }
124
+ };
125
+
126
+ return (
127
+ <Card className={layout?.width === 'full' ? 'w-full' : ''}>
128
+ <CardHeader>
129
+ <CardTitle>{data.title}</CardTitle>
130
+ {data.description && <CardDescription>{data.description}</CardDescription>}
131
+ </CardHeader>
132
+ <CardContent>
133
+ {renderChart()}
134
+ </CardContent>
135
+ </Card>
136
+ );
137
+ }
138
+ ```
139
+
140
+ ### Agent Usage
141
+
142
+ ```typescript
143
+ // Agent sends chart data
144
+ yield* agentUI.sendUI({
145
+ agentId: AGENT_ID,
146
+ conversationId: conversationId,
147
+ component: {
148
+ component: 'chart',
149
+ data: {
150
+ title: 'Revenue Trend (Last 6 Months)',
151
+ description: '20% growth month-over-month',
152
+ chartType: 'line',
153
+ labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
154
+ datasets: [
155
+ {
156
+ label: 'Revenue ($)',
157
+ data: [10000, 12000, 15000, 13000, 18000, 20000],
158
+ color: 'hsl(var(--chart-1))',
159
+ fill: true
160
+ },
161
+ {
162
+ label: 'Profit ($)',
163
+ data: [5000, 6000, 7500, 6500, 9000, 10000],
164
+ color: 'hsl(var(--chart-2))',
165
+ fill: false
166
+ }
167
+ ],
168
+ options: {
169
+ responsive: true,
170
+ maintainAspectRatio: false
171
+ }
172
+ }
173
+ }
174
+ });
175
+ ```
176
+
177
+ ## Pattern 2: DynamicTable (shadcn Table)
178
+
179
+ ### Implementation
180
+
181
+ ```tsx
182
+ import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from '@/components/ui/table';
183
+ import { Card, CardHeader, CardTitle, CardDescription, CardContent } from '@/components/ui/card';
184
+ import { Button } from '@/components/ui/button';
185
+ import type { TableComponentData } from '@/convex/protocols/agent-ui';
186
+ import { useState } from 'react';
187
+
188
+ export function DynamicTable({ data, layout }: {
189
+ data: TableComponentData['data'];
190
+ layout?: any
191
+ }) {
192
+ const [sortColumn, setSortColumn] = useState<number | null>(null);
193
+ const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');
194
+ const [currentPage, setCurrentPage] = useState(1);
195
+
196
+ // Sort rows
197
+ const sortedRows = data.sortable && sortColumn !== null
198
+ ? [...data.rows].sort((a, b) => {
199
+ const aVal = a[sortColumn];
200
+ const bVal = b[sortColumn];
201
+ const direction = sortDirection === 'asc' ? 1 : -1;
202
+ return aVal < bVal ? -direction : aVal > bVal ? direction : 0;
203
+ })
204
+ : data.rows;
205
+
206
+ // Paginate
207
+ const pageSize = data.pagination?.pageSize || 10;
208
+ const paginatedRows = data.pagination
209
+ ? sortedRows.slice((currentPage - 1) * pageSize, currentPage * pageSize)
210
+ : sortedRows;
211
+
212
+ const handleSort = (columnIndex: number) => {
213
+ if (sortColumn === columnIndex) {
214
+ setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
215
+ } else {
216
+ setSortColumn(columnIndex);
217
+ setSortDirection('asc');
218
+ }
219
+ };
220
+
221
+ return (
222
+ <Card className={layout?.width === 'full' ? 'w-full' : ''}>
223
+ <CardHeader>
224
+ <CardTitle>{data.title}</CardTitle>
225
+ {data.description && <CardDescription>{data.description}</CardDescription>}
226
+ </CardHeader>
227
+ <CardContent>
228
+ <Table>
229
+ <TableHeader>
230
+ <TableRow>
231
+ {data.headers.map((header, i) => (
232
+ <TableHead
233
+ key={i}
234
+ onClick={() => data.sortable && handleSort(i)}
235
+ className={data.sortable ? 'cursor-pointer hover:bg-muted' : ''}
236
+ >
237
+ {header}
238
+ {data.sortable && sortColumn === i && (
239
+ <span className="ml-2">{sortDirection === 'asc' ? '↑' : '↓'}</span>
240
+ )}
241
+ </TableHead>
242
+ ))}
243
+ </TableRow>
244
+ </TableHeader>
245
+ <TableBody>
246
+ {paginatedRows.map((row, rowIndex) => (
247
+ <TableRow key={rowIndex}>
248
+ {row.map((cell, cellIndex) => (
249
+ <TableCell key={cellIndex}>{String(cell)}</TableCell>
250
+ ))}
251
+ </TableRow>
252
+ ))}
253
+ </TableBody>
254
+ </Table>
255
+
256
+ {data.pagination && (
257
+ <div className="flex items-center justify-between mt-4">
258
+ <div className="text-sm text-muted-foreground">
259
+ Page {currentPage} of {data.pagination.totalPages}
260
+ </div>
261
+ <div className="flex gap-2">
262
+ <Button
263
+ variant="outline"
264
+ size="sm"
265
+ onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
266
+ disabled={currentPage === 1}
267
+ >
268
+ Previous
269
+ </Button>
270
+ <Button
271
+ variant="outline"
272
+ size="sm"
273
+ onClick={() => setCurrentPage(p => Math.min(data.pagination!.totalPages, p + 1))}
274
+ disabled={currentPage === data.pagination.totalPages}
275
+ >
276
+ Next
277
+ </Button>
278
+ </div>
279
+ </div>
280
+ )}
281
+ </CardContent>
282
+ </Card>
283
+ );
284
+ }
285
+ ```
286
+
287
+ ## Pattern 3: DynamicForm (react-hook-form)
288
+
289
+ ### Implementation
290
+
291
+ ```tsx
292
+ import { useForm } from 'react-hook-form';
293
+ import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from '@/components/ui/card';
294
+ import { Button } from '@/components/ui/button';
295
+ import { Input } from '@/components/ui/input';
296
+ import { Label } from '@/components/ui/label';
297
+ import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '@/components/ui/select';
298
+ import type { FormComponentData } from '@/convex/protocols/agent-ui';
299
+
300
+ export function DynamicForm({ data, layout, onSubmit }: {
301
+ data: FormComponentData['data'];
302
+ layout?: any;
303
+ onSubmit: (data: any) => void;
304
+ }) {
305
+ const { register, handleSubmit, formState: { errors } } = useForm();
306
+
307
+ const renderField = (field: any) => {
308
+ switch (field.type) {
309
+ case 'text':
310
+ case 'email':
311
+ case 'number':
312
+ return (
313
+ <div key={field.name} className="space-y-2">
314
+ <Label htmlFor={field.name}>
315
+ {field.label}
316
+ {field.required && <span className="text-destructive">*</span>}
317
+ </Label>
318
+ <Input
319
+ id={field.name}
320
+ type={field.type}
321
+ {...register(field.name, { required: field.required })}
322
+ defaultValue={field.defaultValue}
323
+ />
324
+ {errors[field.name] && (
325
+ <p className="text-sm text-destructive">This field is required</p>
326
+ )}
327
+ </div>
328
+ );
329
+
330
+ case 'select':
331
+ return (
332
+ <div key={field.name} className="space-y-2">
333
+ <Label htmlFor={field.name}>
334
+ {field.label}
335
+ {field.required && <span className="text-destructive">*</span>}
336
+ </Label>
337
+ <Select {...register(field.name, { required: field.required })}>
338
+ <SelectTrigger>
339
+ <SelectValue placeholder="Select..." />
340
+ </SelectTrigger>
341
+ <SelectContent>
342
+ {field.options?.map((option: string) => (
343
+ <SelectItem key={option} value={option}>
344
+ {option}
345
+ </SelectItem>
346
+ ))}
347
+ </SelectContent>
348
+ </Select>
349
+ </div>
350
+ );
351
+
352
+ default:
353
+ return <div key={field.name}>Unsupported field type: {field.type}</div>;
354
+ }
355
+ };
356
+
357
+ return (
358
+ <Card className={layout?.width === 'full' ? 'w-full' : ''}>
359
+ <CardHeader>
360
+ <CardTitle>{data.title}</CardTitle>
361
+ {data.description && <CardDescription>{data.description}</CardDescription>}
362
+ </CardHeader>
363
+ <CardContent>
364
+ <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
365
+ {data.fields.map(renderField)}
366
+ </form>
367
+ </CardContent>
368
+ <CardFooter>
369
+ <Button type="submit" className="w-full">
370
+ {data.submitLabel || 'Submit'}
371
+ </Button>
372
+ </CardFooter>
373
+ </Card>
374
+ );
375
+ }
376
+ ```
377
+
378
+ ## Best Practices
379
+
380
+ ### Layout and Styling
381
+
382
+ **Responsive Widths:**
383
+ ```typescript
384
+ // Let agent specify width
385
+ layout: {
386
+ width: 'full', // 100% width
387
+ width: 'half', // 50% width (2 columns)
388
+ width: 'third' // 33% width (3 columns)
389
+ }
390
+
391
+ // CSS implementation
392
+ className={
393
+ layout?.width === 'full' ? 'w-full' :
394
+ layout?.width === 'half' ? 'w-full md:w-1/2' :
395
+ layout?.width === 'third' ? 'w-full md:w-1/3' :
396
+ 'w-full'
397
+ }
398
+ ```
399
+
400
+ **Dark Mode Support:**
401
+ ```typescript
402
+ // Use CSS variables (Tailwind v4)
403
+ <div className="bg-background text-foreground">
404
+ <h1 className="text-primary">Title</h1>
405
+ <p className="text-muted-foreground">Description</p>
406
+ </div>
407
+
408
+ // Chart colors
409
+ stroke={dataset.color || `hsl(var(--chart-${i + 1}))`}
410
+ ```
411
+
412
+ ### Accessibility
413
+
414
+ **Keyboard Navigation:**
415
+ ```tsx
416
+ <TableHead
417
+ onClick={() => handleSort(i)}
418
+ onKeyDown={(e) => e.key === 'Enter' && handleSort(i)}
419
+ tabIndex={0}
420
+ role="button"
421
+ aria-label={`Sort by ${header}`}
422
+ >
423
+ {header}
424
+ </TableHead>
425
+ ```
426
+
427
+ **Screen Readers:**
428
+ ```tsx
429
+ <Card role="region" aria-label={data.title}>
430
+ <CardHeader>
431
+ <CardTitle id="chart-title">{data.title}</CardTitle>
432
+ </CardHeader>
433
+ <CardContent aria-labelledby="chart-title">
434
+ {/* Chart */}
435
+ </CardContent>
436
+ </Card>
437
+ ```
438
+
439
+ ### Performance Optimization
440
+
441
+ **Lazy Loading:**
442
+ ```tsx
443
+ import { lazy, Suspense } from 'react';
444
+
445
+ const DynamicChart = lazy(() => import('./DynamicChart'));
446
+ const DynamicTable = lazy(() => import('./DynamicTable'));
447
+
448
+ export function GenerativeUIRenderer({ payload }) {
449
+ return (
450
+ <Suspense fallback={<Skeleton className="h-64" />}>
451
+ {payload.component === 'chart' && <DynamicChart data={payload.data} />}
452
+ {payload.component === 'table' && <DynamicTable data={payload.data} />}
453
+ </Suspense>
454
+ );
455
+ }
456
+ ```
457
+
458
+ **Virtualization:**
459
+ ```tsx
460
+ import { FixedSizeList } from 'react-window';
461
+
462
+ export function VirtualizedTable({ rows }) {
463
+ return (
464
+ <FixedSizeList
465
+ height={400}
466
+ itemCount={rows.length}
467
+ itemSize={50}
468
+ width="100%"
469
+ >
470
+ {({ index, style }) => (
471
+ <TableRow style={style}>
472
+ {rows[index].map((cell, i) => (
473
+ <TableCell key={i}>{cell}</TableCell>
474
+ ))}
475
+ </TableRow>
476
+ )}
477
+ </FixedSizeList>
478
+ );
479
+ }
480
+ ```
481
+
482
+ **Memoization:**
483
+ ```tsx
484
+ import { memo } from 'react';
485
+
486
+ export const DynamicChart = memo(({ data, layout }) => {
487
+ // Expensive chart rendering
488
+ }, (prevProps, nextProps) => {
489
+ return prevProps.data === nextProps.data &&
490
+ prevProps.layout === nextProps.layout;
491
+ });
492
+ ```
493
+
494
+ ## Security Guidelines
495
+
496
+ **Input Sanitization:**
497
+ ```typescript
498
+ // Validate all component data
499
+ const validateChartData = (data: any): ChartComponentData['data'] => {
500
+ if (!data.title || typeof data.title !== 'string') {
501
+ throw new Error('Invalid chart title');
502
+ }
503
+ if (!Array.isArray(data.labels) || data.labels.length > 100) {
504
+ throw new Error('Invalid chart labels');
505
+ }
506
+ // ... more validation
507
+ return data as ChartComponentData['data'];
508
+ };
509
+ ```
510
+
511
+ **Content Security:**
512
+ ```typescript
513
+ // NEVER render user HTML
514
+ ❌ <div dangerouslySetInnerHTML={{ __html: data.content }} />
515
+
516
+ // ALWAYS use structured data
517
+ ✅ <div>{data.content}</div>
518
+ ✅ <DynamicChart data={data.chartData} />
519
+ ```
520
+
521
+ **Action Validation:**
522
+ ```typescript
523
+ // Validate action parameters before execution
524
+ const validateAction = async (actionId: string, params: any) => {
525
+ const action = await db.get(actionId);
526
+ if (!action) throw new Error('Invalid action');
527
+
528
+ // Check user permissions
529
+ const hasPermission = await checkPermission(userId, action.requiredPermission);
530
+ if (!hasPermission) throw new Error('Unauthorized');
531
+
532
+ // Validate parameters
533
+ const validParams = validateParams(params, action.paramSchema);
534
+
535
+ return { action, params: validParams };
536
+ };
537
+ ```
538
+
539
+ ## Summary
540
+
541
+ **Generative UI Patterns provide:**
542
+ - Type-safe component generation
543
+ - Security (no HTML injection)
544
+ - Flexibility (any UI component)
545
+ - Accessibility (WCAG compliant)
546
+ - Performance (lazy loading, virtualization)
547
+
548
+ **Key Benefits:**
549
+ - AI agents can create rich UIs
550
+ - Frontend renders securely
551
+ - Consistent user experience
552
+ - Easy to extend with new components
553
+ - Full TypeScript support
554
+
555
+ **Related Documentation:**
556
+ - [AG-UI Protocol](./ag-ui-protocol.md)
557
+ - [AI SDK Implementation](./ai-sdk-implementation.md)
558
+ - [Component Patterns](../things/patterns/frontend/)
559
+