@bridgebrew/sessions 0.0.0-stage → 0.0.8

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.
Files changed (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +43 -2
  3. package/answers.ts +167 -0
  4. package/browser/branch-actions.tsx +166 -0
  5. package/browser/changes.tsx +415 -0
  6. package/browser/children.tsx +650 -0
  7. package/browser/conversation.tsx +2381 -0
  8. package/browser/decision-questions.tsx +191 -0
  9. package/browser/elapsed.tsx +44 -0
  10. package/browser/gallery.tsx +218 -0
  11. package/browser/index.tsx +3434 -0
  12. package/browser/media-origins.tsx +38 -0
  13. package/browser/mobile.tsx +663 -0
  14. package/browser/open-link.tsx +30 -0
  15. package/browser/pull-request.tsx +116 -0
  16. package/browser/questions.tsx +156 -0
  17. package/browser/session-scheduled.tsx +203 -0
  18. package/browser/subagent-view.tsx +136 -0
  19. package/browser/subagents.tsx +339 -0
  20. package/browser/tabs.tsx +228 -0
  21. package/browser/tsconfig.json +15 -0
  22. package/browser/views/view.tsx +1064 -0
  23. package/browser/views.tsx +166 -0
  24. package/contract.ts +287 -0
  25. package/delegations.ts +1975 -0
  26. package/diff.ts +88 -0
  27. package/docs/en/images.mdx +51 -0
  28. package/docs/en/index.mdx +22 -0
  29. package/docs/en/meta.json +4 -0
  30. package/docs/en/organize-sessions.mdx +53 -0
  31. package/docs/en/start-a-session.mdx +63 -0
  32. package/docs/meta.json +4 -0
  33. package/git.ts +223 -0
  34. package/listing.ts +382 -0
  35. package/package.json +1023 -4
  36. package/peers.ts +677 -0
  37. package/pull-request-watch.ts +282 -0
  38. package/pull-requests.ts +606 -0
  39. package/server.ts +5920 -0
  40. package/text.ts +19 -0
  41. package/tsconfig.json +3 -0
  42. package/viewer-activity.ts +57 -0
  43. package/views/examples.ts +153 -0
  44. package/views/library.ts +1116 -0
@@ -0,0 +1,1064 @@
1
+ // Parts ported from @openuidev/react-lang (MIT, Copyright (c) Thesys Inc.)
2
+ //
3
+ // research-036 (OpenUI POC): draw an OpenUI Lang view with Bridge's kit.
4
+ //
5
+ // The runtime is lang-core's, unchanged: a streaming parser, a store for `$variables`, a query manager for Query()
6
+ // and Mutation(), and the evaluator for props and actions. The port kept only what a page needs — no devtools, no
7
+ // observability, no telemetry, no streaming-observability, no slots. Everything the agent writes is drawn with
8
+ // @bridge/ui; a piece the kit lacks is the closest kit piece, never bare unstyled HTML.
9
+
10
+ import {
11
+ ACTION_STEPS,
12
+ createQueryManager,
13
+ createStore,
14
+ createStreamingParser,
15
+ evaluate,
16
+ evaluateRoot,
17
+ parseStructuredRules,
18
+ resolveStateField,
19
+ type ActionPlan,
20
+ type ActionStep,
21
+ type ElementNode,
22
+ type EvaluationContext,
23
+ type OpenUIError,
24
+ type ParseResult,
25
+ type QueryNode,
26
+ type QuerySnapshot,
27
+ type StateField,
28
+ type Store,
29
+ type ToolProvider,
30
+ type ValidationError,
31
+ validate,
32
+ } from '@openuidev/lang-core';
33
+ import {
34
+ Avatar,
35
+ Badge,
36
+ Button,
37
+ Card,
38
+ CardHeader,
39
+ Checkbox,
40
+ Cluster,
41
+ EmptyState,
42
+ Field,
43
+ FieldDescription,
44
+ FieldError,
45
+ FieldLabel,
46
+ Icon,
47
+ Input,
48
+ Kbd,
49
+ List,
50
+ ListItem,
51
+ Properties,
52
+ PropertyRow,
53
+ Section,
54
+ SegmentGroup,
55
+ Select,
56
+ SelectContent,
57
+ SelectItem,
58
+ SelectTrigger,
59
+ SelectValue,
60
+ Slider,
61
+ StatusIcon,
62
+ Table,
63
+ TableBody,
64
+ TableCell,
65
+ TableHead,
66
+ TableHeader,
67
+ TableRow,
68
+ Tabs,
69
+ TabsContent,
70
+ TabsList,
71
+ TabsTrigger,
72
+ TagPill,
73
+ Textarea,
74
+ Toggle,
75
+ cn,
76
+ type StatusIconStatus,
77
+ } from '@bridge/ui';
78
+ import * as React from 'react';
79
+
80
+ import { libraryFor, type PluginComponent } from '../../views/library.ts';
81
+
82
+ /** What a view calls to read and write a workspace, as the bridge_read and bridge_write MCP tools define it. */
83
+ export interface ViewTools {
84
+ read(plugin: string, path: string, query?: Record<string, string>): Promise<unknown>;
85
+ write(
86
+ plugin: string,
87
+ method: string,
88
+ path: string,
89
+ body?: unknown,
90
+ query?: Record<string, string>,
91
+ ): Promise<unknown>;
92
+ }
93
+
94
+ /** A plugin component a view calls: its plugin, its name, and its evaluated props. */
95
+ export interface ViewComponentCall {
96
+ plugin: string;
97
+ name: string;
98
+ props: Record<string, unknown>;
99
+ }
100
+
101
+ /** Draws a plugin component a view calls (research-036 P2); without one, such a component draws nothing. */
102
+ export type ViewComponentRenderer = (component: ViewComponentCall) => React.ReactNode;
103
+
104
+ export interface ViewProps {
105
+ program: string;
106
+ streaming?: boolean;
107
+ tools: ViewTools;
108
+ onAssistant: (text: string, context?: unknown) => void;
109
+ onErrors?: (errors: OpenUIError[]) => void;
110
+ /** The plugin components the program may use, as the node declares them (research-036 P2). */
111
+ components?: PluginComponent[] | undefined;
112
+ /** Draws each plugin component the program calls, through the plugin's own UI. */
113
+ renderComponent?: ViewComponentRenderer | undefined;
114
+ /** What its queries answered when it was frozen (research-036 P5). With it, no query runs and no action acts. */
115
+ snapshot?: Record<string, unknown> | undefined;
116
+ }
117
+
118
+ /** What an action's writes did: whether one ran, and the refusal that stopped it. */
119
+ interface ActionOutcome {
120
+ wrote: boolean;
121
+ error?: string;
122
+ }
123
+
124
+ /** Props a component receives after the runtime has evaluated them. */
125
+ type RenderProps = Record<string, unknown>;
126
+
127
+ const GAPS: Record<string, string> = { sm: 'gap-2', md: 'gap-3', lg: 'gap-4' };
128
+ const JUSTIFY: Record<string, string> = {
129
+ start: 'justify-start',
130
+ between: 'justify-between',
131
+ end: 'justify-end',
132
+ };
133
+
134
+ const HEADINGS: Record<number, { tag: 'h2' | 'h3' | 'h4'; className: string }> = {
135
+ 1: { tag: 'h2', className: 'text-xl font-semibold text-foreground' },
136
+ 2: { tag: 'h3', className: 'text-sm font-semibold text-foreground' },
137
+ 3: { tag: 'h4', className: 'text-xs font-medium text-secondary' },
138
+ };
139
+
140
+ const TONES: Record<string, string> = {
141
+ default: 'text-sm text-foreground',
142
+ muted: 'text-sm text-muted',
143
+ destructive: 'text-sm text-destructive',
144
+ };
145
+
146
+ function isElement(value: unknown): value is ElementNode {
147
+ return (
148
+ typeof value === 'object' && value !== null && (value as { type?: unknown }).type === 'element'
149
+ );
150
+ }
151
+
152
+ /** Draw a value the evaluator produced: a primitive, an array, or a nested element. */
153
+ function renderValue(value: unknown): React.ReactNode {
154
+ if (value == null || value === false) return null;
155
+ if (typeof value === 'string' || typeof value === 'number') return String(value);
156
+ if (typeof value === 'boolean') return String(value);
157
+ if (Array.isArray(value)) {
158
+ return value.map((item, index) => (
159
+ <React.Fragment key={index}>{renderValue(item)}</React.Fragment>
160
+ ));
161
+ }
162
+ if (isElement(value)) return <RenderNode node={value} />;
163
+ return null;
164
+ }
165
+
166
+ /** Whether an action runs a Mutation: a frozen view draws its button disabled (research-036 P5). */
167
+ function runsMutation(action: unknown): boolean {
168
+ const steps = (action as ActionPlan | undefined)?.steps;
169
+ if (!Array.isArray(steps)) return false;
170
+ return steps.some((step) => step.type === ACTION_STEPS.Run && step.refType === 'mutation');
171
+ }
172
+
173
+ /** The URL an action only opens (its one step an @OpenUrl): its button is a link, so a click follows Bridge's rule. */
174
+ function linkOf(action: unknown): string | undefined {
175
+ const steps = (action as ActionPlan | undefined)?.steps;
176
+ if (!Array.isArray(steps) || steps.length !== 1) return undefined;
177
+ const [step] = steps;
178
+ return step?.type === ACTION_STEPS.OpenUrl ? step.url : undefined;
179
+ }
180
+
181
+ /** A link's anchor: one of this origin (a Bridge screen) in place, where the shell's link rule follows it (research-048:
182
+ * a plain click here, ⌘ or a middle click beside, ⌥ on a new desk); another in a new tab, which gets no `opener`.
183
+ * None for a URL that does not parse: its button says so instead of breaking the whole view. */
184
+ function anchorOf(url: string): React.ReactElement | undefined {
185
+ if (!URL.canParse(url, location.href)) return undefined;
186
+ const inBridge = new URL(url, location.href).origin === location.origin;
187
+ return inBridge ? <a href={url} /> : <a href={url} target="_blank" rel="noopener noreferrer" />;
188
+ }
189
+
190
+ // ─── The view context the renderers share ───────────────────────────────────
191
+
192
+ interface ViewContextValue {
193
+ /** Runs a button's action; resolves with what its writes did (none: `wrote` false). */
194
+ triggerAction: (label: string, action: unknown) => Promise<ActionOutcome>;
195
+ store: Store;
196
+ evaluationContext: EvaluationContext;
197
+ isStreaming: boolean;
198
+ /** A frozen view (research-036 P5): its actions do nothing and its mutation buttons are disabled. */
199
+ frozen: boolean;
200
+ /** Draws a plugin component by its type name; null when the view has no renderer for plugins. */
201
+ renderPlugin: (name: string, props: RenderProps) => React.ReactNode;
202
+ }
203
+
204
+ const ViewContext = React.createContext<ViewContextValue | null>(null);
205
+
206
+ function useView(): ViewContextValue {
207
+ const context = React.useContext(ViewContext);
208
+ if (!context) throw new Error('View components must render inside <View>.');
209
+ return context;
210
+ }
211
+
212
+ /** Bind a control to its `$variable` (or to a plain named value when it has no binding). */
213
+ function useBoundValue(name: string, value: unknown): StateField<unknown> {
214
+ const { store, evaluationContext } = useView();
215
+ return resolveStateField(
216
+ name,
217
+ value,
218
+ store,
219
+ evaluationContext,
220
+ (key) => store.get(key),
221
+ (key, next) => store.set(key, next),
222
+ );
223
+ }
224
+
225
+ /** A Form's fields: each control registers how to check its value; a button of the form checks them all first. */
226
+ interface FormValue {
227
+ register: (name: string, check: () => string | undefined) => () => void;
228
+ /** Checks every field, shows their messages; true when all pass. */
229
+ checkAll: () => boolean;
230
+ /** Checks one field again once it shows a message (as the user fixes it). */
231
+ recheck: (name: string) => void;
232
+ errors: Record<string, string>;
233
+ }
234
+
235
+ const FormContext = React.createContext<FormValue | null>(null);
236
+
237
+ /** Registers control `name`'s `rules` with its Form; its message, if it shows one. */
238
+ function useRules(name: string, rules: unknown, value: unknown): string | undefined {
239
+ const form = React.useContext(FormContext);
240
+ const valueRef = React.useRef(value);
241
+ valueRef.current = value;
242
+ const key = JSON.stringify(rules ?? null);
243
+ const parsed = React.useMemo(() => (rules == null ? [] : parseStructuredRules(rules)), [key]);
244
+ const register = form?.register;
245
+ React.useEffect(
246
+ () =>
247
+ register && parsed.length
248
+ ? register(name, () => validate(valueRef.current, parsed))
249
+ : undefined,
250
+ [register, name, parsed],
251
+ );
252
+ const error = form?.errors[name];
253
+ const recheck = form?.recheck;
254
+ React.useEffect(() => {
255
+ if (error !== undefined) recheck?.(name);
256
+ }, [value]);
257
+ return error;
258
+ }
259
+
260
+ // ─── Component renderers ────────────────────────────────────────────────────
261
+
262
+ function StackRenderer({ props }: { props: RenderProps }) {
263
+ const gap = typeof props.gap === 'string' ? props.gap : 'md';
264
+ return (
265
+ <div className={cn('flex min-w-0 flex-col', GAPS[gap] ?? GAPS.md)}>
266
+ {renderValue(props.children)}
267
+ </div>
268
+ );
269
+ }
270
+
271
+ function ClusterRenderer({ props }: { props: RenderProps }) {
272
+ const justify = typeof props.justify === 'string' ? props.justify : 'start';
273
+ return (
274
+ <Cluster className={JUSTIFY[justify] ?? JUSTIFY.start}>{renderValue(props.children)}</Cluster>
275
+ );
276
+ }
277
+
278
+ function CardRenderer({ props }: { props: RenderProps }) {
279
+ const title = props.title == null ? undefined : String(props.title);
280
+ const description = props.description == null ? undefined : String(props.description);
281
+ return (
282
+ <Card>
283
+ {title != null || description != null ? (
284
+ <CardHeader>
285
+ <div className="flex min-w-0 flex-col gap-0.5">
286
+ {title != null && (
287
+ <span className="truncate text-sm font-semibold text-foreground">{title}</span>
288
+ )}
289
+ {description != null && <span className="text-xs text-muted">{description}</span>}
290
+ </div>
291
+ </CardHeader>
292
+ ) : null}
293
+ {renderValue(props.children)}
294
+ </Card>
295
+ );
296
+ }
297
+
298
+ function SectionRenderer({ props }: { props: RenderProps }) {
299
+ return (
300
+ <Section
301
+ title={String(props.title ?? '')}
302
+ description={props.description == null ? undefined : String(props.description)}
303
+ >
304
+ {renderValue(props.children)}
305
+ </Section>
306
+ );
307
+ }
308
+
309
+ function TabsRenderer({ props }: { props: RenderProps }) {
310
+ const tabs = (props.tabs as ElementNode[] | undefined) ?? [];
311
+ const first = tabs[0] ? String(tabs[0].props.label ?? '') : '';
312
+ return (
313
+ <Tabs defaultValue={first}>
314
+ <TabsList>
315
+ {tabs.map((tab, index) => (
316
+ <TabsTrigger key={index} value={String(tab.props.label ?? index)}>
317
+ {String(tab.props.label ?? '')}
318
+ </TabsTrigger>
319
+ ))}
320
+ </TabsList>
321
+ {tabs.map((tab, index) => (
322
+ <TabsContent key={index} value={String(tab.props.label ?? index)}>
323
+ {renderValue(tab.props.children)}
324
+ </TabsContent>
325
+ ))}
326
+ </Tabs>
327
+ );
328
+ }
329
+
330
+ function TabRenderer({ props }: { props: RenderProps }) {
331
+ return <>{renderValue(props.children)}</>;
332
+ }
333
+
334
+ function HeadingRenderer({ props }: { props: RenderProps }) {
335
+ const level = props.level === 2 ? 2 : props.level === 3 ? 3 : 1;
336
+ const { tag: Tag, className } = HEADINGS[level] ?? HEADINGS[1]!;
337
+ return <Tag className={cn('min-w-0 truncate', className)}>{String(props.text ?? '')}</Tag>;
338
+ }
339
+
340
+ function TextRenderer({ props }: { props: RenderProps }) {
341
+ const tone = typeof props.tone === 'string' ? props.tone : 'default';
342
+ return <p className={cn('m-0', TONES[tone] ?? TONES.default)}>{String(props.text ?? '')}</p>;
343
+ }
344
+
345
+ function KbdRenderer({ props }: { props: RenderProps }) {
346
+ return <Kbd>{String(props.keys ?? '')}</Kbd>;
347
+ }
348
+
349
+ function IconRenderer({ props }: { props: RenderProps }) {
350
+ return <Icon name={String(props.name ?? '')} />;
351
+ }
352
+
353
+ function BadgeRenderer({ props }: { props: RenderProps }) {
354
+ return <Badge>{renderValue(props.text)}</Badge>;
355
+ }
356
+
357
+ function TagPillRenderer({ props }: { props: RenderProps }) {
358
+ const size = props.size === 'sm' ? 'sm' : 'default';
359
+ return <TagPill name={String(props.label ?? '')} size={size} />;
360
+ }
361
+
362
+ function AvatarRenderer({ props }: { props: RenderProps }) {
363
+ const sizes = ['xs', 'sm', 'default', 'lg', 'xl', '2xl', '3xl'] as const;
364
+ const size = sizes.find((each) => each === props.size) ?? 'default';
365
+ const shape = props.shape === 'square' ? 'square' : 'circle';
366
+ return <Avatar name={String(props.name ?? '')} size={size} shape={shape} />;
367
+ }
368
+
369
+ function StatusIconRenderer({ props }: { props: RenderProps }) {
370
+ return <StatusIcon status={props.status as StatusIconStatus} />;
371
+ }
372
+
373
+ function EmptyStateRenderer({ props }: { props: RenderProps }) {
374
+ const icon = props.icon == null ? undefined : <Icon name={String(props.icon)} />;
375
+ return (
376
+ <EmptyState icon={icon} title={String(props.title ?? '')}>
377
+ {props.description == null ? null : <p>{String(props.description)}</p>}
378
+ </EmptyState>
379
+ );
380
+ }
381
+
382
+ function TableRenderer({ props }: { props: RenderProps }) {
383
+ const columns = (props.columns as ElementNode[] | undefined) ?? [];
384
+ const rows = (props.rows as unknown[][] | undefined) ?? [];
385
+ const template = columns.map((column) => String(column.props.width ?? '1fr')).join(' ');
386
+ return (
387
+ <Table columns={template}>
388
+ <TableHeader>
389
+ <TableRow>
390
+ {columns.map((column, index) => (
391
+ <TableHead key={index}>{String(column.props.label ?? '')}</TableHead>
392
+ ))}
393
+ </TableRow>
394
+ </TableHeader>
395
+ <TableBody>
396
+ {rows.map((row, rowIndex) => (
397
+ <TableRow key={rowIndex}>
398
+ {columns.map((_column, columnIndex) => (
399
+ <TableCell key={columnIndex}>{renderValue(row[columnIndex])}</TableCell>
400
+ ))}
401
+ </TableRow>
402
+ ))}
403
+ </TableBody>
404
+ </Table>
405
+ );
406
+ }
407
+
408
+ function ColRenderer() {
409
+ return null;
410
+ }
411
+
412
+ function PropertiesRenderer({ props }: { props: RenderProps }) {
413
+ return <Properties>{renderValue(props.items)}</Properties>;
414
+ }
415
+
416
+ function PropertyRenderer({ props }: { props: RenderProps }) {
417
+ const value = props.value;
418
+ return (
419
+ <PropertyRow label={String(props.label ?? '')}>
420
+ {typeof value === 'string' || typeof value === 'number' ? (
421
+ <span className="text-sm text-foreground">{String(value)}</span>
422
+ ) : (
423
+ renderValue(value)
424
+ )}
425
+ </PropertyRow>
426
+ );
427
+ }
428
+
429
+ function ListRenderer({ props }: { props: RenderProps }) {
430
+ return <List>{renderValue(props.items)}</List>;
431
+ }
432
+
433
+ function ListItemRenderer({ props }: { props: RenderProps }) {
434
+ const { triggerAction } = useView();
435
+ const title = String(props.title ?? '');
436
+ const action = props.action;
437
+ return (
438
+ <ListItem
439
+ textValue={title}
440
+ leading={props.leading == null ? undefined : renderValue(props.leading)}
441
+ description={props.subtitle == null ? undefined : String(props.subtitle)}
442
+ trailing={props.trailing == null ? undefined : renderValue(props.trailing)}
443
+ onClick={
444
+ action == null
445
+ ? undefined
446
+ : () => {
447
+ // A row has no room to say what its write did: only a failure that throws is logged.
448
+ void triggerAction(title, action).catch((cause: unknown) =>
449
+ console.warn('[views]', cause),
450
+ );
451
+ }
452
+ }
453
+ >
454
+ {title}
455
+ </ListItem>
456
+ );
457
+ }
458
+
459
+ function FormRenderer({ props }: { props: RenderProps }) {
460
+ const checks = React.useRef(new Map<string, () => string | undefined>());
461
+ const [errors, setErrors] = React.useState<Record<string, string>>({});
462
+ const register = React.useCallback((name: string, check: () => string | undefined) => {
463
+ checks.current.set(name, check);
464
+ return () => {
465
+ checks.current.delete(name);
466
+ };
467
+ }, []);
468
+ const checkAll = React.useCallback(() => {
469
+ const next: Record<string, string> = {};
470
+ for (const [name, check] of checks.current) {
471
+ const message = check();
472
+ if (message !== undefined) next[name] = message;
473
+ }
474
+ setErrors(next);
475
+ return Object.keys(next).length === 0;
476
+ }, []);
477
+ const recheck = React.useCallback((name: string) => {
478
+ const message = checks.current.get(name)?.();
479
+ setErrors(({ [name]: _was, ...rest }) =>
480
+ message === undefined ? rest : { ...rest, [name]: message },
481
+ );
482
+ }, []);
483
+ const form = React.useMemo(
484
+ () => ({ register, checkAll, recheck, errors }),
485
+ [register, checkAll, recheck, errors],
486
+ );
487
+ return (
488
+ <FormContext.Provider value={form}>
489
+ <form
490
+ className="flex min-w-0 flex-col gap-3"
491
+ onSubmit={(event) => {
492
+ event.preventDefault();
493
+ }}
494
+ >
495
+ {renderValue(props.children)}
496
+ {renderValue(props.buttons)}
497
+ </form>
498
+ </FormContext.Provider>
499
+ );
500
+ }
501
+
502
+ function FieldRenderer({ props }: { props: RenderProps }) {
503
+ const form = React.useContext(FormContext);
504
+ const control = isElement(props.control) ? props.control : undefined;
505
+ const error =
506
+ control && typeof control.props.name === 'string'
507
+ ? form?.errors[control.props.name]
508
+ : undefined;
509
+ return (
510
+ <Field invalid={error !== undefined}>
511
+ <FieldLabel>{String(props.label ?? '')}</FieldLabel>
512
+ {renderValue(props.control)}
513
+ {props.description == null ? null : (
514
+ <FieldDescription>{String(props.description)}</FieldDescription>
515
+ )}
516
+ {error !== undefined && <FieldError>{error}</FieldError>}
517
+ </Field>
518
+ );
519
+ }
520
+
521
+ function InputRenderer({ props }: { props: RenderProps }) {
522
+ const name = String(props.name ?? '');
523
+ const field = useBoundValue(name, props.value);
524
+ const error = useRules(name, props.rules, field.value);
525
+ return (
526
+ <Input
527
+ variant="outline"
528
+ name={name}
529
+ type={typeof props.type === 'string' ? props.type : 'text'}
530
+ placeholder={props.placeholder == null ? undefined : String(props.placeholder)}
531
+ value={field.value == null ? '' : String(field.value)}
532
+ aria-invalid={error !== undefined || undefined}
533
+ onChange={(event) => field.setValue(event.target.value)}
534
+ />
535
+ );
536
+ }
537
+
538
+ function TextareaRenderer({ props }: { props: RenderProps }) {
539
+ const name = String(props.name ?? '');
540
+ const field = useBoundValue(name, props.value);
541
+ const error = useRules(name, props.rules, field.value);
542
+ return (
543
+ <Textarea
544
+ variant="outline"
545
+ name={name}
546
+ placeholder={props.placeholder == null ? undefined : String(props.placeholder)}
547
+ value={field.value == null ? '' : String(field.value)}
548
+ aria-invalid={error !== undefined || undefined}
549
+ onChange={(event) => field.setValue(event.target.value)}
550
+ />
551
+ );
552
+ }
553
+
554
+ function SelectRenderer({ props }: { props: RenderProps }) {
555
+ const name = String(props.name ?? '');
556
+ const field = useBoundValue(name, props.value);
557
+ const options = ((props.options as ElementNode[] | undefined) ?? []).map((option) => ({
558
+ value: String(option.props.value ?? ''),
559
+ label: String(option.props.label ?? ''),
560
+ }));
561
+ const value = field.value == null ? null : String(field.value);
562
+ return (
563
+ <Select
564
+ items={options}
565
+ value={value}
566
+ onValueChange={(next) => field.setValue(next == null ? '' : String(next))}
567
+ >
568
+ <SelectTrigger>
569
+ <SelectValue
570
+ placeholder={props.placeholder == null ? 'Choose' : String(props.placeholder)}
571
+ />
572
+ </SelectTrigger>
573
+ <SelectContent>
574
+ {options.map((option) => (
575
+ <SelectItem key={option.value} value={option.value}>
576
+ {option.label}
577
+ </SelectItem>
578
+ ))}
579
+ </SelectContent>
580
+ </Select>
581
+ );
582
+ }
583
+
584
+ function OptionRenderer() {
585
+ return null;
586
+ }
587
+
588
+ function CheckboxRenderer({ props }: { props: RenderProps }) {
589
+ const name = String(props.name ?? '');
590
+ const field = useBoundValue(name, props.value);
591
+ return (
592
+ <label className="flex items-center gap-2 text-sm text-foreground">
593
+ <Checkbox
594
+ checked={field.value === true}
595
+ onCheckedChange={(next) => field.setValue(next === true)}
596
+ />
597
+ <span>{String(props.label ?? '')}</span>
598
+ </label>
599
+ );
600
+ }
601
+
602
+ function ToggleRenderer({ props }: { props: RenderProps }) {
603
+ const name = String(props.name ?? '');
604
+ const field = useBoundValue(name, props.value);
605
+ return (
606
+ <label className="flex items-center justify-between gap-3 text-sm text-foreground">
607
+ <span>{String(props.label ?? '')}</span>
608
+ <Toggle
609
+ checked={field.value === true}
610
+ onCheckedChange={(next) => field.setValue(next === true)}
611
+ />
612
+ </label>
613
+ );
614
+ }
615
+
616
+ function SliderRenderer({ props }: { props: RenderProps }) {
617
+ const name = String(props.name ?? '');
618
+ const field = useBoundValue(name, props.value);
619
+ const min = props.min == null ? 0 : Number(props.min);
620
+ const value = typeof field.value === 'number' ? field.value : min;
621
+ return (
622
+ <Slider
623
+ min={min}
624
+ max={props.max == null ? 100 : Number(props.max)}
625
+ step={props.step == null ? undefined : Number(props.step)}
626
+ value={value}
627
+ onValueChange={(next: number | number[]) =>
628
+ field.setValue(Array.isArray(next) ? next[0] : next)
629
+ }
630
+ />
631
+ );
632
+ }
633
+
634
+ function SegmentGroupRenderer({ props }: { props: RenderProps }) {
635
+ const name = String(props.name ?? '');
636
+ const field = useBoundValue(name, props.value);
637
+ const options = ((props.options as ElementNode[] | undefined) ?? []).map((option) => ({
638
+ value: String(option.props.value ?? ''),
639
+ label: String(option.props.label ?? ''),
640
+ }));
641
+ const value = field.value == null ? (options[0]?.value ?? '') : String(field.value);
642
+ return (
643
+ <SegmentGroup
644
+ items={options}
645
+ value={value}
646
+ onValueChange={(next: string) => field.setValue(next)}
647
+ />
648
+ );
649
+ }
650
+
651
+ function ButtonRenderer({ props }: { props: RenderProps }) {
652
+ const { triggerAction, frozen } = useView();
653
+ const form = React.useContext(FormContext);
654
+ const label = String(props.label ?? '');
655
+ const variant = props.variant as 'primary' | 'outline' | 'ghost' | 'destructive' | undefined;
656
+ const action = props.action;
657
+ const link = linkOf(action);
658
+ // What its last write did, said beside it: a save that shows nothing gets clicked again.
659
+ const [state, setState] = React.useState<
660
+ { busy: true } | { busy: false; saved?: boolean; error?: string }
661
+ >({ busy: false });
662
+ React.useEffect(() => {
663
+ if (state.busy || !state.saved) return;
664
+ const timer = setTimeout(() => setState({ busy: false }), 3000);
665
+ return () => clearTimeout(timer);
666
+ }, [state]);
667
+ if (link !== undefined) {
668
+ const anchor = anchorOf(link);
669
+ return anchor ? (
670
+ <Button variant={variant} render={anchor}>
671
+ {label}
672
+ </Button>
673
+ ) : (
674
+ <Button variant={variant} disabled title={`Not a valid address: ${link}`}>
675
+ {label}
676
+ </Button>
677
+ );
678
+ }
679
+ return (
680
+ <span className="inline-flex items-center gap-2">
681
+ {!state.busy && state.saved && <span className="text-sm text-muted">Saved</span>}
682
+ {!state.busy && state.error !== undefined && (
683
+ <span role="alert" className="text-sm text-destructive">
684
+ {state.error}
685
+ </span>
686
+ )}
687
+ <Button
688
+ variant={variant}
689
+ disabled={state.busy || (frozen && runsMutation(action))}
690
+ onClick={() => {
691
+ // A form's button that acts (not a Reset) checks the form first.
692
+ const resets = (action as ActionPlan | undefined)?.steps?.every(
693
+ (step) => step.type === ACTION_STEPS.Reset,
694
+ );
695
+ if (form && action != null && !resets && !form.checkAll()) return;
696
+ setState({ busy: true });
697
+ triggerAction(label, action)
698
+ .then(({ wrote, error }) =>
699
+ setState(
700
+ error !== undefined ? { busy: false, error } : { busy: false, saved: wrote },
701
+ ),
702
+ )
703
+ .catch((cause: unknown) =>
704
+ setState({
705
+ busy: false,
706
+ error: cause instanceof Error ? cause.message : String(cause),
707
+ }),
708
+ );
709
+ }}
710
+ >
711
+ {label}
712
+ </Button>
713
+ </span>
714
+ );
715
+ }
716
+
717
+ function ButtonsRenderer({ props }: { props: RenderProps }) {
718
+ return <Cluster>{renderValue(props.children)}</Cluster>;
719
+ }
720
+
721
+ const RENDERERS: Record<string, (props: { props: RenderProps }) => React.ReactNode> = {
722
+ Stack: StackRenderer,
723
+ Cluster: ClusterRenderer,
724
+ Card: CardRenderer,
725
+ Section: SectionRenderer,
726
+ Tabs: TabsRenderer,
727
+ Tab: TabRenderer,
728
+ Heading: HeadingRenderer,
729
+ Text: TextRenderer,
730
+ Kbd: KbdRenderer,
731
+ Icon: IconRenderer,
732
+ Table: TableRenderer,
733
+ Col: ColRenderer,
734
+ Properties: PropertiesRenderer,
735
+ Property: PropertyRenderer,
736
+ List: ListRenderer,
737
+ ListItem: ListItemRenderer,
738
+ Badge: BadgeRenderer,
739
+ TagPill: TagPillRenderer,
740
+ Avatar: AvatarRenderer,
741
+ StatusIcon: StatusIconRenderer,
742
+ EmptyState: EmptyStateRenderer,
743
+ Form: FormRenderer,
744
+ Field: FieldRenderer,
745
+ Input: InputRenderer,
746
+ Textarea: TextareaRenderer,
747
+ Select: SelectRenderer,
748
+ Option: OptionRenderer,
749
+ Checkbox: CheckboxRenderer,
750
+ Toggle: ToggleRenderer,
751
+ Slider: SliderRenderer,
752
+ SegmentGroup: SegmentGroupRenderer,
753
+ Button: ButtonRenderer,
754
+ Buttons: ButtonsRenderer,
755
+ };
756
+
757
+ function RenderNode({ node }: { node: ElementNode }): React.ReactNode {
758
+ const { renderPlugin } = useView();
759
+ const Renderer = RENDERERS[node.typeName];
760
+ if (Renderer) return <Renderer props={node.props} />;
761
+ // A plugin's component: drawn by its plugin through `renderComponent`, or nothing without one.
762
+ return renderPlugin(node.typeName, node.props) ?? null;
763
+ }
764
+
765
+ function toOpenUIError(error: ValidationError): OpenUIError {
766
+ return {
767
+ source: 'parser',
768
+ code: error.code,
769
+ message: error.message,
770
+ ...(error.statementId !== undefined ? { statementId: error.statementId } : {}),
771
+ ...(error.component ? { component: error.component } : {}),
772
+ ...(error.path ? { path: error.path } : {}),
773
+ };
774
+ }
775
+
776
+ // ─── The view ───────────────────────────────────────────────────────────────
777
+
778
+ /** Draw an OpenUI Lang program with the kit, over lang-core's runtime. */
779
+ export function View({
780
+ program,
781
+ streaming,
782
+ tools,
783
+ onAssistant,
784
+ onErrors,
785
+ components,
786
+ renderComponent,
787
+ snapshot,
788
+ }: ViewProps) {
789
+ /** A frozen view (research-036 P5): it draws from `snapshot` and calls no route. */
790
+ const frozen = snapshot !== undefined;
791
+ const pluginComponents = React.useMemo(() => components ?? [], [components]);
792
+ const componentsKey = JSON.stringify(pluginComponents);
793
+ // The kit plus the node's plugin components (research-036 P2), rebuilt when their declarations change.
794
+ const viewLibrary = React.useMemo(() => libraryFor(pluginComponents), [componentsKey]);
795
+ const parser = React.useMemo(
796
+ () => createStreamingParser(viewLibrary.toJSONSchema(), viewLibrary.root),
797
+ [viewLibrary],
798
+ );
799
+ const result = React.useMemo<ParseResult | null>(() => {
800
+ try {
801
+ return parser.set(program, !streaming);
802
+ } catch {
803
+ return null;
804
+ }
805
+ }, [parser, program, streaming]);
806
+
807
+ const store = React.useMemo<Store>(() => createStore(), []);
808
+
809
+ // The tools are read from a ref, so swapping them never rebuilds the query manager (and its cache).
810
+ const toolsRef = React.useRef(tools);
811
+ toolsRef.current = tools;
812
+ const toolProvider = React.useMemo<ToolProvider>(
813
+ () => ({
814
+ async callTool(toolName: string, args: Record<string, unknown>) {
815
+ const current = toolsRef.current;
816
+ const query = args.query as Record<string, string> | undefined;
817
+ if (toolName === 'bridge_read') {
818
+ return current.read(String(args.plugin ?? ''), String(args.path ?? ''), query);
819
+ }
820
+ if (toolName === 'bridge_write') {
821
+ return current.write(
822
+ String(args.plugin ?? ''),
823
+ String(args.method ?? ''),
824
+ String(args.path ?? ''),
825
+ args.body,
826
+ query,
827
+ );
828
+ }
829
+ throw new Error(`[views] unknown tool "${toolName}"`);
830
+ },
831
+ }),
832
+ [],
833
+ );
834
+ const queryManager = React.useMemo(() => createQueryManager(toolProvider), [toolProvider]);
835
+
836
+ React.useEffect(() => {
837
+ if (frozen) return;
838
+ queryManager.activate();
839
+ return () => queryManager.dispose();
840
+ }, [queryManager, frozen]);
841
+
842
+ // Declared defaults fill the store; a value the user already set is kept.
843
+ React.useEffect(() => {
844
+ store.initialize(result?.stateDeclarations ?? {}, {});
845
+ }, [store, result?.stateDeclarations]);
846
+
847
+ const storeSnapshot = React.useSyncExternalStore(
848
+ store.subscribe,
849
+ store.getSnapshot,
850
+ store.getSnapshot,
851
+ );
852
+ const querySnapshot = React.useSyncExternalStore(
853
+ queryManager.subscribe,
854
+ queryManager.getSnapshot,
855
+ queryManager.getSnapshot,
856
+ ) as QuerySnapshot;
857
+
858
+ // A frozen view's queries: each successful answer kept with it, else the query's defaults (research-036 P5).
859
+ const queryDefaults = React.useMemo(() => {
860
+ const defaults = new Map<string, unknown>();
861
+ const scoped: EvaluationContext = {
862
+ getState: (name: string) => store.get(name),
863
+ resolveRef: () => null,
864
+ };
865
+ for (const query of result?.queryStatements ?? []) {
866
+ if (query.defaultsAST === null) continue;
867
+ try {
868
+ defaults.set(query.statementId, evaluate(query.defaultsAST, scoped));
869
+ } catch {
870
+ defaults.set(query.statementId, null);
871
+ }
872
+ }
873
+ return defaults;
874
+ }, [result?.queryStatements, store, storeSnapshot]);
875
+
876
+ const evaluationContext = React.useMemo<EvaluationContext>(
877
+ () => ({
878
+ getState: (name: string) => store.get(name),
879
+ resolveRef: (name: string) => {
880
+ if (snapshot !== undefined)
881
+ return Object.hasOwn(snapshot, name) ? snapshot[name] : (queryDefaults.get(name) ?? null);
882
+ return queryManager.getMutationResult(name) ?? queryManager.getResult(name);
883
+ },
884
+ }),
885
+ [store, queryManager, snapshot, queryDefaults],
886
+ );
887
+
888
+ // The plugin of each component name, by the declarations' JSON (the library's key); two plugins with one name (install
889
+ // refuses it): the first, as the library keeps it.
890
+ const pluginOf = React.useMemo(() => {
891
+ const found = new Map<string, string>();
892
+ for (const each of pluginComponents)
893
+ if (!found.has(each.name)) found.set(each.name, each.plugin);
894
+ return found;
895
+ }, [componentsKey]);
896
+ const renderPlugin = React.useCallback(
897
+ (name: string, props: RenderProps) => {
898
+ const plugin = pluginOf.get(name);
899
+ if (plugin === undefined || !renderComponent) return null;
900
+ return renderComponent({ plugin, name, props });
901
+ },
902
+ [pluginOf, renderComponent],
903
+ );
904
+
905
+ // Evaluate and submit every Query(); an empty list clears the ones that went away. A frozen view runs none.
906
+ React.useEffect(() => {
907
+ if (frozen) return;
908
+ const nodes: QueryNode[] = (result?.queryStatements ?? []).map((query) => {
909
+ const deps: Record<string, unknown> = {};
910
+ for (const ref of query.deps ?? []) deps[ref] = storeSnapshot[ref];
911
+ return {
912
+ statementId: query.statementId,
913
+ toolName: query.toolAST ? String(evaluate(query.toolAST, evaluationContext) ?? '') : '',
914
+ args: query.argsAST ? evaluate(query.argsAST, evaluationContext) : null,
915
+ defaults: query.defaultsAST ? evaluate(query.defaultsAST, evaluationContext) : null,
916
+ ...(query.refreshAST
917
+ ? { refreshInterval: Number(evaluate(query.refreshAST, evaluationContext)) }
918
+ : {}),
919
+ deps: Object.keys(deps).length > 0 ? deps : undefined,
920
+ complete: query.complete,
921
+ };
922
+ });
923
+ queryManager.evaluateQueries(nodes);
924
+ }, [frozen, result?.queryStatements, evaluationContext, queryManager, storeSnapshot]);
925
+
926
+ // Register every Mutation() so an @Run step can fire it (a frozen view fires none).
927
+ React.useEffect(() => {
928
+ if (frozen) return;
929
+ queryManager.registerMutations(
930
+ (result?.mutationStatements ?? []).map((mutation) => ({
931
+ statementId: mutation.statementId,
932
+ toolName: mutation.toolAST ? String(evaluate(mutation.toolAST, evaluationContext)) : '',
933
+ })),
934
+ );
935
+ }, [frozen, result?.mutationStatements, evaluationContext, queryManager]);
936
+
937
+ const runtimeErrors = React.useRef<OpenUIError[]>([]);
938
+
939
+ // Evaluate the tree: props, `$variables`, expressions and Query results, once per store or query change (the two
940
+ // snapshots are the deps that report those changes).
941
+ const root = React.useMemo<ElementNode | null>(() => {
942
+ if (!result || (!result.root && !result.rootExpression)) return null;
943
+ const errors: OpenUIError[] = [];
944
+ try {
945
+ const evaluated = evaluateRoot(result, {
946
+ ctx: evaluationContext,
947
+ library: viewLibrary,
948
+ store,
949
+ errors,
950
+ });
951
+ runtimeErrors.current = errors;
952
+ return evaluated;
953
+ } catch (error) {
954
+ runtimeErrors.current = [
955
+ ...errors,
956
+ {
957
+ source: 'runtime',
958
+ code: 'runtime-error',
959
+ message: `Prop evaluation failed: ${error instanceof Error ? error.message : String(error)}`,
960
+ },
961
+ ];
962
+ return result.root;
963
+ }
964
+ }, [result, evaluationContext, store, storeSnapshot, querySnapshot, viewLibrary]);
965
+
966
+ const parseErrors = React.useMemo(() => (result?.meta.errors ?? []).map(toOpenUIError), [result]);
967
+
968
+ React.useEffect(() => {
969
+ const errors = [...parseErrors, ...runtimeErrors.current];
970
+ if (errors.length > 0) onErrors?.(errors);
971
+ }, [parseErrors, onErrors]);
972
+
973
+ const resultRef = React.useRef(result);
974
+ resultRef.current = result;
975
+ const onAssistantRef = React.useRef(onAssistant);
976
+ onAssistantRef.current = onAssistant;
977
+
978
+ /** Runs an action's steps in order; a mutation is awaited, and one that fails stops the steps after it. In a frozen
979
+ * view (research-036 P5), a step that would run or reach outside does nothing; local state still works. */
980
+ const runSteps = React.useCallback(
981
+ async (steps: ActionStep[]): Promise<ActionOutcome> => {
982
+ let wrote = false;
983
+ for (const step of steps) {
984
+ switch (step.type) {
985
+ case ACTION_STEPS.Run: {
986
+ if (frozen) break;
987
+ if (step.refType === 'mutation') {
988
+ const mutation = resultRef.current?.mutationStatements.find(
989
+ (each) => each.statementId === step.statementId,
990
+ );
991
+ const args = mutation?.argsAST
992
+ ? (evaluate(mutation.argsAST, evaluationContext) as Record<string, unknown>)
993
+ : {};
994
+ if (!(await queryManager.fireMutation(step.statementId, args))) {
995
+ const failed = queryManager.getMutationResult(step.statementId);
996
+ const error =
997
+ failed !== null && typeof failed === 'object' && 'error' in failed
998
+ ? String(failed.error)
999
+ : 'The change failed.';
1000
+ return { wrote, error };
1001
+ }
1002
+ wrote = true;
1003
+ } else {
1004
+ queryManager.invalidate([step.statementId]);
1005
+ }
1006
+ break;
1007
+ }
1008
+ case ACTION_STEPS.ToAssistant:
1009
+ if (frozen) break;
1010
+ if (step.context === undefined) onAssistantRef.current(step.message);
1011
+ else onAssistantRef.current(step.message, step.context);
1012
+ break;
1013
+ // A link writes nothing: a frozen view opens it too.
1014
+ case ACTION_STEPS.OpenUrl:
1015
+ window.open(step.url, '_blank', 'noopener');
1016
+ break;
1017
+ case ACTION_STEPS.Set:
1018
+ store.set(step.target, evaluate(step.valueAST, evaluationContext));
1019
+ break;
1020
+ case ACTION_STEPS.Reset: {
1021
+ const declarations = resultRef.current?.stateDeclarations ?? {};
1022
+ for (const target of step.targets) {
1023
+ store.set(target, declarations[target] ?? null, { pristine: true });
1024
+ }
1025
+ break;
1026
+ }
1027
+ default:
1028
+ break;
1029
+ }
1030
+ }
1031
+ return { wrote };
1032
+ },
1033
+ [evaluationContext, frozen, queryManager, store],
1034
+ );
1035
+
1036
+ /** A button or a row acting: its action's steps, or, with none, its label handed to the session (OpenUI's rule). */
1037
+ const triggerAction = React.useCallback(
1038
+ async (label: string, action: unknown): Promise<ActionOutcome> => {
1039
+ const plan = action as ActionPlan | undefined;
1040
+ if (plan == null) onAssistantRef.current(label);
1041
+ else if (Array.isArray(plan.steps)) return runSteps(plan.steps);
1042
+ return { wrote: false };
1043
+ },
1044
+ [runSteps],
1045
+ );
1046
+
1047
+ const contextValue = React.useMemo<ViewContextValue>(
1048
+ () => ({
1049
+ triggerAction,
1050
+ store,
1051
+ evaluationContext,
1052
+ isStreaming: streaming === true,
1053
+ frozen,
1054
+ renderPlugin,
1055
+ }),
1056
+ [triggerAction, store, evaluationContext, streaming, frozen, renderPlugin],
1057
+ );
1058
+
1059
+ return (
1060
+ <ViewContext.Provider value={contextValue}>
1061
+ {root ? <RenderNode node={root} /> : null}
1062
+ </ViewContext.Provider>
1063
+ );
1064
+ }