@oaiz/app-kit 0.0.0-stage → 0.1.4128

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 (107) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +143 -2
  3. package/THIRD_PARTY_NOTICES.md +76 -0
  4. package/package.json +139 -4
  5. package/registry.json +1847 -0
  6. package/src/components/activity-timeline.tsx +227 -0
  7. package/src/components/app-shell.tsx +622 -0
  8. package/src/components/bar-list.tsx +47 -0
  9. package/src/components/board.tsx +700 -0
  10. package/src/components/calendar-view.tsx +1388 -0
  11. package/src/components/card-grid.tsx +462 -0
  12. package/src/components/charts.tsx +701 -0
  13. package/src/components/chat-markdown.tsx +230 -0
  14. package/src/components/chat-panel.tsx +760 -0
  15. package/src/components/code-editor.tsx +276 -0
  16. package/src/components/collection-controls.tsx +226 -0
  17. package/src/components/command-palette.tsx +403 -0
  18. package/src/components/confirm-action.tsx +123 -0
  19. package/src/components/data-table.tsx +821 -0
  20. package/src/components/date-input.tsx +429 -0
  21. package/src/components/empty-state.tsx +31 -0
  22. package/src/components/error-state.tsx +37 -0
  23. package/src/components/file-upload.tsx +595 -0
  24. package/src/components/filter-bar.tsx +415 -0
  25. package/src/components/grouped-picker.tsx +250 -0
  26. package/src/components/line-items.tsx +601 -0
  27. package/src/components/list-view.tsx +491 -0
  28. package/src/components/metrics.tsx +53 -0
  29. package/src/components/page-header.tsx +33 -0
  30. package/src/components/property-picker.tsx +546 -0
  31. package/src/components/record-detail.tsx +416 -0
  32. package/src/components/record-form.tsx +295 -0
  33. package/src/components/record-name.tsx +85 -0
  34. package/src/components/save-bar.tsx +142 -0
  35. package/src/components/sign-in.tsx +179 -0
  36. package/src/components/split-view.tsx +128 -0
  37. package/src/components/status-dot.tsx +56 -0
  38. package/src/components/stepper.tsx +153 -0
  39. package/src/components/text-diff-model.ts +111 -0
  40. package/src/components/text-diff.tsx +98 -0
  41. package/src/components/time-zone-picker.tsx +69 -0
  42. package/src/components/ui/accordion.tsx +138 -0
  43. package/src/components/ui/alert-dialog.tsx +67 -0
  44. package/src/components/ui/alert.tsx +65 -0
  45. package/src/components/ui/avatar-group.tsx +119 -0
  46. package/src/components/ui/avatar.tsx +55 -0
  47. package/src/components/ui/badge.tsx +59 -0
  48. package/src/components/ui/bottom-navigation.tsx +102 -0
  49. package/src/components/ui/breadcrumb.tsx +117 -0
  50. package/src/components/ui/button.tsx +71 -0
  51. package/src/components/ui/card.tsx +95 -0
  52. package/src/components/ui/checkbox.tsx +31 -0
  53. package/src/components/ui/collapsible.tsx +27 -0
  54. package/src/components/ui/context-menu.tsx +270 -0
  55. package/src/components/ui/count-up.tsx +136 -0
  56. package/src/components/ui/detail-disclosure-section.tsx +109 -0
  57. package/src/components/ui/dialog.tsx +157 -0
  58. package/src/components/ui/dropdown-menu.tsx +273 -0
  59. package/src/components/ui/form-field.tsx +155 -0
  60. package/src/components/ui/heading.tsx +126 -0
  61. package/src/components/ui/hover-card.tsx +45 -0
  62. package/src/components/ui/input.tsx +50 -0
  63. package/src/components/ui/label.tsx +30 -0
  64. package/src/components/ui/orb-spinner.tsx +238 -0
  65. package/src/components/ui/popover.tsx +59 -0
  66. package/src/components/ui/progress-ring.tsx +125 -0
  67. package/src/components/ui/progress.tsx +38 -0
  68. package/src/components/ui/radio-group.tsx +124 -0
  69. package/src/components/ui/resizable.tsx +48 -0
  70. package/src/components/ui/scroll-fade.tsx +98 -0
  71. package/src/components/ui/segmented-control.tsx +70 -0
  72. package/src/components/ui/select.tsx +230 -0
  73. package/src/components/ui/separator.tsx +29 -0
  74. package/src/components/ui/sheet.tsx +170 -0
  75. package/src/components/ui/shimmer-text.tsx +87 -0
  76. package/src/components/ui/shortcut.tsx +39 -0
  77. package/src/components/ui/skeleton.tsx +15 -0
  78. package/src/components/ui/slider.tsx +48 -0
  79. package/src/components/ui/switch.tsx +44 -0
  80. package/src/components/ui/table.tsx +119 -0
  81. package/src/components/ui/tabs.tsx +80 -0
  82. package/src/components/ui/text.tsx +93 -0
  83. package/src/components/ui/textarea.tsx +51 -0
  84. package/src/components/ui/toast.tsx +141 -0
  85. package/src/components/ui/toaster.tsx +40 -0
  86. package/src/components/ui/tooltip.tsx +38 -0
  87. package/src/components/ui/top-banner.tsx +108 -0
  88. package/src/components/ui/tree-view.tsx +215 -0
  89. package/src/components/ui/use-toast.tsx +184 -0
  90. package/src/components/ui/voice-orb.tsx +252 -0
  91. package/src/hooks/oaiz-chat.tsx +530 -0
  92. package/src/hooks/oaiz-data.tsx +617 -0
  93. package/src/hooks/oaiz-session.tsx +63 -0
  94. package/src/hooks/use-arrivals.ts +19 -0
  95. package/src/hooks/use-breakpoint.ts +100 -0
  96. package/src/hooks/use-media-query.ts +36 -0
  97. package/src/hooks/use-theme.ts +67 -0
  98. package/src/hooks/use-url-state.ts +77 -0
  99. package/src/lib/breakpoints.ts +81 -0
  100. package/src/lib/csp-nonce.ts +15 -0
  101. package/src/lib/format.ts +291 -0
  102. package/src/lib/speech-level.ts +118 -0
  103. package/src/lib/utils.ts +109 -0
  104. package/src/styles/oaiz/app.css +21 -0
  105. package/src/styles/oaiz/scrollbars.css +20 -0
  106. package/src/styles/oaiz/tokens.css +952 -0
  107. package/src/styles/oaiz/voice-orb.css +39 -0
@@ -0,0 +1,760 @@
1
+ import { Textarea } from './ui/textarea';
2
+ import {
3
+ memo,
4
+ useLayoutEffect,
5
+ useRef,
6
+ useState,
7
+ type FormEvent,
8
+ type KeyboardEvent,
9
+ type ReactNode,
10
+ } from 'react';
11
+ import {
12
+ AlertCircle,
13
+ ArrowDown,
14
+ ArrowUp,
15
+ AudioLines,
16
+ Check,
17
+ ChevronRight,
18
+ Copy,
19
+ Loader2,
20
+ Mic,
21
+ MicOff,
22
+ ShieldAlert,
23
+ Square,
24
+ X,
25
+ } from 'lucide-react';
26
+
27
+ import type {
28
+ ChatItem,
29
+ OaizChatStatus,
30
+ OaizChatVoiceControls,
31
+ PendingToolCall,
32
+ } from '../hooks/oaiz-chat';
33
+ import { cn } from '../lib/utils';
34
+ import { ChatMarkdown, useCopy } from './chat-markdown';
35
+ import { Avatar, AvatarFallback } from './ui/avatar';
36
+ import { Button } from './ui/button';
37
+ import { Heading } from './ui/heading';
38
+ import { OrbSpinner } from './ui/orb-spinner';
39
+ import { ShimmerText } from './ui/shimmer-text';
40
+ import { Skeleton } from './ui/skeleton';
41
+ import { Text } from './ui/text';
42
+ import { VoiceOrb } from './ui/voice-orb';
43
+
44
+ export type ChatPanelProps = {
45
+ items: ChatItem[];
46
+ status: OaizChatStatus;
47
+ onSend: (content: string) => unknown;
48
+ /** Closes the stream, which stops the turn. */
49
+ onStop: () => void;
50
+ /** The greeting above the centred composer of an empty chat. */
51
+ empty?: ReactNode;
52
+ /** Shown below the centred composer of an empty chat, such as suggested questions. */
53
+ emptyFooter?: ReactNode;
54
+ /** The chat's saved messages are loading. */
55
+ loading?: boolean;
56
+ /** Why the last message failed; the row with it offers `onRetry`. */
57
+ error?: { message: string } | null;
58
+ onRetry?: () => void;
59
+ /** The `voice` of `useOaizChat`; the panel offers voice when it is set. */
60
+ voice?: OaizChatVoiceControls | null;
61
+ /**
62
+ * The `pending` call of `useOaizChat`. The panel shows it with `onApprove` and `onDecline`, and
63
+ * sends no message until the member decides.
64
+ */
65
+ pending?: PendingToolCall | null;
66
+ onApprove?: () => void;
67
+ onDecline?: () => void;
68
+ placeholder?: string;
69
+ className?: string;
70
+ };
71
+
72
+ const NEAR_END_PX = 80;
73
+
74
+ const ROW_TRIGGER =
75
+ 'flex w-full min-w-0 items-center gap-inline rounded-lg p-inset text-left text-muted-foreground transition-colors duration-fast ease-move hover:bg-muted/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring';
76
+ const ROW_CHEVRON = 'size-4 shrink-0 transition-transform duration-fast ease-move';
77
+ const ROW_SPINNER =
78
+ 'size-3.5 shrink-0 animate-spin text-muted-foreground motion-reduce:animate-none';
79
+ const HOVER_ACTIONS =
80
+ 'mt-1 flex items-center gap-inline transition-opacity duration-fast ease-move group-focus-within:opacity-100 group-hover:opacity-100 [@media(hover:hover)]:opacity-0';
81
+ const STEP_RAIL = 'mt-1 ml-2 flex flex-col gap-3 border-l border-border py-2 pl-6';
82
+
83
+ type Activity = Extract<ChatItem, { kind: 'reasoning' | 'tool' }>;
84
+ type Message = Extract<ChatItem, { kind: 'user' | 'answer' }>;
85
+ type TimelineRow = { kind: 'activity'; id: string; steps: Activity[] } | Message;
86
+
87
+ /** Each run of reasoning and tools between messages becomes one activity row. */
88
+ function toTimeline(items: ChatItem[]): TimelineRow[] {
89
+ const rows: TimelineRow[] = [];
90
+ for (const item of items) {
91
+ if (item.kind === 'user' || item.kind === 'answer') {
92
+ rows.push(item);
93
+ continue;
94
+ }
95
+ const last = rows[rows.length - 1];
96
+ if (last?.kind === 'activity') last.steps.push(item);
97
+ else rows.push({ kind: 'activity', id: item.id, steps: [item] });
98
+ }
99
+ return rows;
100
+ }
101
+
102
+ function formatDuration(ms: number | undefined): string | null {
103
+ if (!ms || ms <= 0) return null;
104
+ if (ms < 1000) return `${Math.round(ms)}ms`;
105
+ if (ms < 60_000) return `${(ms / 1000).toFixed(2)}s`;
106
+ const seconds = Math.round(ms / 1000);
107
+ return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
108
+ }
109
+
110
+ function formatTime(createdAt: string): string {
111
+ return new Date(createdAt).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
112
+ }
113
+
114
+ function MessageActions({
115
+ content,
116
+ createdAt,
117
+ align,
118
+ }: {
119
+ content: string;
120
+ createdAt?: string;
121
+ align: 'start' | 'end';
122
+ }) {
123
+ const { copied, copy } = useCopy();
124
+ const time = createdAt ? (
125
+ <Text asChild size="xs" variant="muted">
126
+ <time dateTime={createdAt}>{formatTime(createdAt)}</time>
127
+ </Text>
128
+ ) : null;
129
+ return (
130
+ <div className={cn(HOVER_ACTIONS, align === 'end' ? 'justify-end' : 'justify-start')}>
131
+ {align === 'end' && time}
132
+ <Button
133
+ variant="ghost"
134
+ size="icon-xs"
135
+ className="text-muted-foreground"
136
+ aria-label={copied ? 'Copied' : 'Copy message'}
137
+ onClick={() => void copy(content)}
138
+ >
139
+ {copied ? <Check /> : <Copy />}
140
+ </Button>
141
+ {align === 'start' && time}
142
+ </div>
143
+ );
144
+ }
145
+
146
+ function WorkingLabel({ label }: { label: string }) {
147
+ return (
148
+ <span className="flex min-w-0 items-center gap-inline">
149
+ <OrbSpinner sizePx={20} aria-hidden />
150
+ <ShimmerText appearance="activity" size="sm" className="text-foreground">
151
+ {label}
152
+ </ShimmerText>
153
+ </span>
154
+ );
155
+ }
156
+
157
+ function Json({ title, value }: { title: string; value: Record<string, unknown> }) {
158
+ return (
159
+ <div>
160
+ <Text size="xs" variant="muted" className="mb-1">
161
+ {title}
162
+ </Text>
163
+ <pre tabIndex={0} className="max-h-64 overflow-auto rounded-md bg-muted p-inset font-mono text-xs leading-relaxed text-foreground">
164
+ {JSON.stringify(value, null, 2)}
165
+ </pre>
166
+ </div>
167
+ );
168
+ }
169
+
170
+ function Disclosure({
171
+ header,
172
+ railClassName,
173
+ children,
174
+ testId,
175
+ }: {
176
+ header: ReactNode;
177
+ railClassName: string;
178
+ children?: ReactNode;
179
+ testId: string;
180
+ }) {
181
+ const [open, setOpen] = useState(false);
182
+ if (!children) {
183
+ return (
184
+ <div
185
+ className="flex w-full min-w-0 items-center gap-inline p-inset pl-[2.25rem] text-muted-foreground"
186
+ data-testid={testId}
187
+ >
188
+ {header}
189
+ </div>
190
+ );
191
+ }
192
+ return (
193
+ <div className="flex w-full min-w-0 flex-col" data-testid={testId}>
194
+ <Button variant="plain" size={null}
195
+ type="button"
196
+ className={ROW_TRIGGER}
197
+ aria-expanded={open}
198
+ onClick={() => setOpen(!open)}
199
+ >
200
+ <ChevronRight aria-hidden className={cn(ROW_CHEVRON, open && 'rotate-90')} />
201
+ {header}
202
+ </Button>
203
+ {open && <div className={railClassName}>{children}</div>}
204
+ </div>
205
+ );
206
+ }
207
+
208
+ function StepName({ name }: { name: string }) {
209
+ return (
210
+ <Text as="span" weight="medium" variant="muted" className="min-w-0 flex-1 truncate" title={name}>
211
+ {name}
212
+ </Text>
213
+ );
214
+ }
215
+
216
+ function StepMeta({ children }: { children: ReactNode }) {
217
+ return (
218
+ <Text as="span" size="xs" variant="muted" className="shrink-0">
219
+ {children}
220
+ </Text>
221
+ );
222
+ }
223
+
224
+ function ActivityStep({ step }: { step: Activity }) {
225
+ const duration = formatDuration(step.durationMs);
226
+ if (step.kind === 'reasoning') {
227
+ return (
228
+ <Disclosure
229
+ testId="chat-panel-reasoning"
230
+ railClassName={STEP_RAIL}
231
+ header={
232
+ <>
233
+ <StepName name="Reasoning" />
234
+ {step.streaming && <Loader2 className={ROW_SPINNER} />}
235
+ {duration && <StepMeta>{duration}</StepMeta>}
236
+ </>
237
+ }
238
+ >
239
+ {step.content ? (
240
+ <Text as="p" variant="muted" leading="relaxed" className="break-words whitespace-pre-wrap">
241
+ {step.content}
242
+ </Text>
243
+ ) : null}
244
+ </Disclosure>
245
+ );
246
+ }
247
+ return (
248
+ <Disclosure
249
+ testId="chat-panel-tool"
250
+ railClassName={STEP_RAIL}
251
+ header={
252
+ <>
253
+ <StepName name={step.name} />
254
+ {step.state === 'running' && <Loader2 className={ROW_SPINNER} />}
255
+ {step.state === 'stopped' && <StepMeta>Stopped</StepMeta>}
256
+ {step.state === 'waiting' && <StepMeta>Waiting for approval</StepMeta>}
257
+ {step.state === 'failed' && (
258
+ <span className="shrink-0">
259
+ <X aria-hidden className="size-3.5 text-destructive-text" />
260
+ <span className="sr-only">Failed</span>
261
+ </span>
262
+ )}
263
+ {duration && <StepMeta>{duration}</StepMeta>}
264
+ </>
265
+ }
266
+ >
267
+ {step.input || step.output || step.error ? (
268
+ <>
269
+ {step.input && <Json title="Input" value={step.input} />}
270
+ {step.output && <Json title="Output" value={step.output} />}
271
+ {step.error && (
272
+ <Text as="p" variant="destructive" className="break-words">
273
+ {step.error}
274
+ </Text>
275
+ )}
276
+ </>
277
+ ) : null}
278
+ </Disclosure>
279
+ );
280
+ }
281
+
282
+ function ActivityRow({ steps, active }: { steps: Activity[]; active: boolean }) {
283
+ const last = steps[steps.length - 1];
284
+ const ending =
285
+ last?.kind === 'tool' && last.state === 'waiting'
286
+ ? 'Waiting for approval'
287
+ : last?.kind === 'tool' && last.state === 'stopped'
288
+ ? 'Stopped'
289
+ : 'Completed';
290
+ return (
291
+ <div className="mb-2 flex w-full">
292
+ <Disclosure
293
+ testId="chat-panel-activity"
294
+ railClassName="mt-1 ml-2 max-h-[25rem] scrollbar-none overflow-y-auto overscroll-contain border-l border-border pr-0.5 pl-2"
295
+ header={
296
+ active ? (
297
+ <WorkingLabel label="Working.." />
298
+ ) : (
299
+ <>
300
+ <Text as="span" weight="medium" variant="muted" className="min-w-0 truncate">
301
+ {`${ending} · ${steps.length} ${steps.length === 1 ? 'step' : 'steps'}`}
302
+ </Text>
303
+ {last?.kind === 'tool' && last.state === 'failed' && (
304
+ <span className="shrink-0">
305
+ <X aria-hidden className="size-3.5 text-muted-foreground" />
306
+ <span className="sr-only">The last step failed</span>
307
+ </span>
308
+ )}
309
+ </>
310
+ )
311
+ }
312
+ >
313
+ {steps.map((step) => (
314
+ <ActivityStep key={step.id} step={step} />
315
+ ))}
316
+ </Disclosure>
317
+ </div>
318
+ );
319
+ }
320
+
321
+ const MessageRow = memo(function MessageRow({ item }: { item: Message }) {
322
+ if (item.kind === 'user') {
323
+ return (
324
+ <div
325
+ className="group mb-chat-message-gap flex w-full justify-end"
326
+ data-testid="chat-panel-user"
327
+ >
328
+ <div className="ml-8 flex max-w-[calc(100%-2rem)] min-w-0 flex-col mobile:max-w-[85%]">
329
+ <div className="max-w-[37.5rem] rounded-lg bg-muted p-inset break-words">
330
+ <Text as="div" leading="relaxed" className="whitespace-pre-wrap">
331
+ {item.content}
332
+ </Text>
333
+ </div>
334
+ <MessageActions content={item.content} createdAt={item.createdAt} align="end" />
335
+ </div>
336
+ </div>
337
+ );
338
+ }
339
+ return (
340
+ <div
341
+ className="group mb-chat-message-gap flex w-full justify-start"
342
+ data-testid="chat-panel-answer"
343
+ aria-busy={item.streaming}
344
+ >
345
+ <div className="mr-8 flex min-w-0 flex-1 flex-col break-words">
346
+ <ChatMarkdown content={item.content} streaming={item.streaming} />
347
+ {!item.streaming && (
348
+ <MessageActions content={item.content} createdAt={item.createdAt} align="start" />
349
+ )}
350
+ </div>
351
+ </div>
352
+ );
353
+ });
354
+
355
+ function ApprovalRow({
356
+ call,
357
+ deciding,
358
+ onApprove,
359
+ onDecline,
360
+ }: {
361
+ call: PendingToolCall;
362
+ /** A decision on the call is on its way. */
363
+ deciding: boolean;
364
+ onApprove?: () => void;
365
+ onDecline?: () => void;
366
+ }) {
367
+ return (
368
+ <div
369
+ role="group"
370
+ aria-label="Tool call waiting for approval"
371
+ className="mb-chat-message-gap flex flex-col gap-inline rounded-lg border border-warning-text/50 bg-warning-bg-subtle p-inset"
372
+ data-testid="chat-panel-approval"
373
+ >
374
+ <div className="flex items-center gap-inline">
375
+ <ShieldAlert aria-hidden className="size-4 shrink-0 text-warning-text" />
376
+ <Text as="span" weight="medium" className="min-w-0 truncate">
377
+ {`Run ${call.displayName || call.toolName}?`}
378
+ </Text>
379
+ </div>
380
+ <Text size="sm" variant="muted">
381
+ The agent waits for your decision. The call runs only if you approve it.
382
+ </Text>
383
+ <Json title="Input" value={call.args} />
384
+ <div className="flex justify-end gap-inline">
385
+ <Button variant="outline" size="sm" onClick={onDecline} disabled={deciding} data-testid="chat-panel-decline">
386
+ <X /> Decline
387
+ </Button>
388
+ <Button size="sm" onClick={onApprove} disabled={deciding} data-testid="chat-panel-approve">
389
+ <Check /> Approve
390
+ </Button>
391
+ </div>
392
+ </div>
393
+ );
394
+ }
395
+
396
+ function ChatError({ message, onRetry }: { message: string; onRetry?: () => void }) {
397
+ return (
398
+ <div
399
+ role="alert"
400
+ className="mb-chat-message-gap flex w-full max-w-full items-start gap-3 mobile:max-w-[85%]"
401
+ >
402
+ <Avatar className="mt-1 size-8 shrink-0">
403
+ <AvatarFallback className="border border-destructive-text bg-destructive-bg-subtle text-destructive-text">
404
+ <AlertCircle className="size-4" />
405
+ </AvatarFallback>
406
+ </Avatar>
407
+ <div className="flex min-w-0 flex-col items-start gap-inline">
408
+ <div className="rounded-lg border border-destructive-text bg-destructive-bg-subtle p-inset">
409
+ <Text
410
+ as="div"
411
+ variant="destructive"
412
+ leading="relaxed"
413
+ className="break-words whitespace-pre-wrap"
414
+ >
415
+ {message}
416
+ </Text>
417
+ </div>
418
+ {onRetry && (
419
+ <Button variant="outline" size="xs" onClick={onRetry}>
420
+ Try again
421
+ </Button>
422
+ )}
423
+ </div>
424
+ </div>
425
+ );
426
+ }
427
+
428
+ /** The line the voice model is speaking right now. */
429
+ function VoiceTranscript({ speech }: { speech: string }) {
430
+ if (!speech) return null;
431
+ return (
432
+ <p
433
+ className="max-h-24 min-w-0 flex-1 overflow-y-auto py-1 text-sm text-muted-foreground"
434
+ aria-live="polite"
435
+ data-testid="chat-panel-voice-transcript"
436
+ >
437
+ <span className="sr-only">Said aloud: </span>
438
+ {speech}
439
+ </p>
440
+ );
441
+ }
442
+
443
+ /** Starts the call on an empty composer, and ends a call in progress. */
444
+ function VoiceButton({ voice, loading }: { voice: OaizChatVoiceControls; loading: boolean }) {
445
+ const { state } = voice;
446
+ const live = state === 'live';
447
+ const pending = state === 'connecting' || state === 'closing';
448
+ const label =
449
+ state === 'connecting'
450
+ ? 'Connecting the voice conversation'
451
+ : live
452
+ ? 'End'
453
+ : state === 'closing'
454
+ ? 'Ending the voice conversation'
455
+ : 'Start a voice conversation';
456
+ return (
457
+ <Button
458
+ type="button"
459
+ variant={live ? 'default' : 'ghost'}
460
+ size="icon"
461
+ disabled={state === 'closing' || (state === 'idle' && loading)}
462
+ aria-label={label}
463
+ aria-pressed={live}
464
+ aria-busy={pending}
465
+ className={cn(
466
+ 'size-10 shrink-0 half:size-8',
467
+ live
468
+ ? 'rounded-full bg-foreground p-0 text-background shadow-sm hover:bg-foreground/90'
469
+ : 'rounded-md text-foreground hover:bg-transparent hover:text-foreground',
470
+ )}
471
+ data-testid="chat-panel-voice"
472
+ onClick={(event) => {
473
+ event.stopPropagation();
474
+ if (state === 'idle') void voice.start();
475
+ else voice.stop();
476
+ }}
477
+ >
478
+ {pending ? (
479
+ <Loader2 className="animate-spin motion-reduce:animate-none" />
480
+ ) : live ? (
481
+ <Square className="!size-3.5 fill-current" />
482
+ ) : (
483
+ <AudioLines />
484
+ )}
485
+ </Button>
486
+ );
487
+ }
488
+
489
+ /**
490
+ * A chat in the style of OAIZ chat. It fills its parent, so give the parent a height. An empty chat
491
+ * centres its composer below `empty`. Each run of reasoning and tools collapses into one row, and
492
+ * the answer streams as Markdown. Enter sends, Shift+Enter starts a new line, and the send button
493
+ * stops the turn while the agent works. With `voice`, an empty composer offers a call instead, and
494
+ * during a call it holds the End control. The view stays on the newest row unless the member
495
+ * scrolls up, and then a button leads back.
496
+ */
497
+ export function ChatPanel({
498
+ items,
499
+ status,
500
+ onSend,
501
+ onStop,
502
+ empty,
503
+ emptyFooter,
504
+ loading = false,
505
+ error,
506
+ onRetry,
507
+ voice,
508
+ pending,
509
+ onApprove,
510
+ onDecline,
511
+ placeholder = 'Ask a question',
512
+ className,
513
+ }: ChatPanelProps) {
514
+ const [draft, setDraft] = useState('');
515
+ const [awayFromEnd, setAwayFromEnd] = useState(false);
516
+ const input = useRef<HTMLTextAreaElement>(null);
517
+ const scroller = useRef<HTMLDivElement>(null);
518
+ const followNewest = useRef(true);
519
+ const working = status !== 'idle';
520
+ const hasDraft = draft.trim() !== '';
521
+ const voiceState = voice?.state ?? 'idle';
522
+ const inCall = voiceState !== 'idle';
523
+ const callChanging = voiceState === 'connecting' || voiceState === 'closing';
524
+ const deciding = pending != null;
525
+ const canSend = hasDraft && !loading && !callChanging && !deciding;
526
+ // A spoken request runs as a chat turn, so the agent works for most of a call, and the member
527
+ // must still be able to hang up. Starting a call still defers to a draft or a running turn.
528
+ const showVoiceButton = voice != null && !hasDraft && (inCall || (!working && !deciding));
529
+ const rows = toTimeline(items);
530
+ const lastRow = rows[rows.length - 1];
531
+ const activeRun = working && lastRow?.kind === 'activity';
532
+ const centred = items.length === 0 && !working && !loading && !error && !voice?.error && !deciding;
533
+
534
+ useLayoutEffect(() => {
535
+ if (scroller.current && followNewest.current) {
536
+ scroller.current.scrollTop = scroller.current.scrollHeight;
537
+ }
538
+ });
539
+
540
+ useLayoutEffect(() => {
541
+ if (!input.current) return;
542
+ input.current.style.height = 'auto';
543
+ input.current.style.height = `${input.current.scrollHeight}px`;
544
+ }, [draft]);
545
+
546
+ function submit() {
547
+ const content = draft.trim();
548
+ // A call runs its messages one after the other, so a message typed during a turn waits for it.
549
+ if (content === '' || (working && !inCall) || loading || callChanging || deciding) return;
550
+ followNewest.current = true;
551
+ setAwayFromEnd(false);
552
+ setDraft('');
553
+ onSend(content);
554
+ }
555
+
556
+ function handleSubmit(event: FormEvent<HTMLFormElement>) {
557
+ event.preventDefault();
558
+ if (working) onStop();
559
+ else submit();
560
+ input.current?.focus();
561
+ }
562
+
563
+ function handleKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
564
+ if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent.isComposing) {
565
+ event.preventDefault();
566
+ submit();
567
+ }
568
+ }
569
+
570
+ // The scroll handler resumes following on arrival; a render before that would cut the motion short.
571
+ function scrollToEnd() {
572
+ // A scroll option overrides CSS scroll-behavior, so reduced motion is read here.
573
+ const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
574
+ scroller.current?.scrollTo({ top: scroller.current.scrollHeight, behavior: reduce ? 'auto' : 'smooth' });
575
+ }
576
+
577
+ const composer = (
578
+ <form className="relative w-full" onSubmit={handleSubmit} data-testid="chat-panel-composer">
579
+ {awayFromEnd && !centred && (
580
+ <Button
581
+ type="button"
582
+ variant="outline"
583
+ size="icon"
584
+ className="absolute -top-12 left-1/2 z-20 size-8 -translate-x-1/2 rounded-full border-border/60 bg-background/95 shadow-lg backdrop-blur-sm hover:bg-background hover:shadow-xl"
585
+ aria-label="Scroll to the latest message"
586
+ data-testid="chat-panel-scroll-to-latest"
587
+ onClick={scrollToEnd}
588
+ >
589
+ <ArrowDown />
590
+ </Button>
591
+ )}
592
+ <div
593
+ className="flex w-full cursor-text flex-col gap-inline rounded-lg border border-border bg-card p-inset shadow-xs"
594
+ onClick={() => input.current?.focus()}
595
+ >
596
+ {voice && inCall && !centred && (
597
+ <div className="flex w-full items-center gap-inline" data-testid="chat-panel-voice-composer">
598
+ <VoiceOrb size="composer" state={voiceState} outputAnalyser={voice.outputAnalyser} />
599
+ <VoiceTranscript speech={voice.assistantSpeech} />
600
+ </div>
601
+ )}
602
+ <div className="flex w-full items-start gap-inline">
603
+ <Textarea
604
+ ref={input}
605
+ rows={1}
606
+ value={draft}
607
+ placeholder={placeholder}
608
+ aria-label={placeholder}
609
+ className="max-h-60 min-h-8 min-w-0 flex-1 resize-none"
610
+ data-testid="chat-panel-input"
611
+ onChange={(event) => setDraft(event.target.value)}
612
+ onKeyDown={handleKeyDown}
613
+ />
614
+ {voice && inCall && voiceState !== 'closing' && (
615
+ <Button
616
+ type="button"
617
+ variant="ghost"
618
+ size="icon"
619
+ aria-label={voice.muted ? 'Unmute microphone' : 'Mute microphone'}
620
+ aria-pressed={voice.muted}
621
+ className={cn(
622
+ 'size-10 shrink-0 rounded-md half:size-8',
623
+ voice.muted ? 'text-muted-foreground hover:text-foreground' : 'text-foreground hover:text-foreground',
624
+ )}
625
+ data-testid="chat-panel-voice-mute"
626
+ onClick={(event) => {
627
+ event.stopPropagation();
628
+ voice.toggleMute();
629
+ }}
630
+ >
631
+ {voice.muted ? <MicOff /> : <Mic />}
632
+ </Button>
633
+ )}
634
+ {voice && showVoiceButton ? (
635
+ <VoiceButton voice={voice} loading={loading} />
636
+ ) : (
637
+ <Button
638
+ type="submit"
639
+ size="sm"
640
+ disabled={!working && !canSend}
641
+ aria-label={working ? 'Stop' : 'Send'}
642
+ className={cn(
643
+ 'size-10 shrink-0 rounded-full p-0 shadow-sm transition-all duration-normal half:size-8',
644
+ working || canSend
645
+ ? 'bg-foreground text-background hover:bg-foreground/90'
646
+ : 'border border-border/60 bg-background text-muted-foreground hover:bg-background disabled:opacity-100',
647
+ canSend && !working && 'hover:scale-105',
648
+ )}
649
+ data-testid="chat-panel-submit"
650
+ >
651
+ {working ? <Square className="!size-3.5 fill-current" /> : <ArrowUp className="!size-5" />}
652
+ </Button>
653
+ )}
654
+ </div>
655
+ </div>
656
+ </form>
657
+ );
658
+
659
+ // One tree for both layouts, so the composer keeps its focus when the first message docks it.
660
+ return (
661
+ <div
662
+ ref={scroller}
663
+ role="group"
664
+ aria-label="Chat"
665
+ tabIndex={0}
666
+ className={cn(
667
+ 'flex h-full min-h-0 w-full flex-col overflow-y-auto bg-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring',
668
+ centred && 'justify-center',
669
+ className,
670
+ )}
671
+ data-testid="chat-panel"
672
+ onScroll={({ currentTarget: { scrollHeight, scrollTop, clientHeight } }) => {
673
+ const nearEnd = scrollHeight - scrollTop - clientHeight < NEAR_END_PX;
674
+ followNewest.current = nearEnd;
675
+ setAwayFromEnd(!nearEnd);
676
+ }}
677
+ >
678
+ {centred && voice && inCall ? (
679
+ <div
680
+ className="mx-auto mb-stack flex w-full max-w-3xl flex-col items-center gap-3 px-3 text-center half:mb-6 half:px-4"
681
+ data-testid="chat-panel-voice-stage"
682
+ >
683
+ <VoiceOrb size="stage" state={voiceState} outputAnalyser={voice.outputAnalyser} />
684
+ <Heading level={1}>I&apos;m listening.</Heading>
685
+ <VoiceTranscript speech={voice.assistantSpeech} />
686
+ </div>
687
+ ) : (
688
+ centred &&
689
+ empty && (
690
+ <div
691
+ className="mx-auto mb-stack flex w-full max-w-3xl flex-col items-center gap-1 px-3 text-center half:mb-6 half:px-4"
692
+ data-testid="chat-panel-empty"
693
+ >
694
+ {empty}
695
+ </div>
696
+ )
697
+ )}
698
+ <div className={cn('w-full flex-1 px-3 pt-stack half:px-4', centred && 'hidden')}>
699
+ <div
700
+ role="log"
701
+ aria-label="Conversation"
702
+ aria-busy={working || loading}
703
+ className="mx-auto flex min-h-full w-full max-w-3xl flex-col"
704
+ >
705
+ {loading ? (
706
+ <div className="flex flex-col gap-stack" data-testid="chat-panel-loading">
707
+ <Skeleton className="ml-auto h-11 w-2/5 rounded-lg" />
708
+ <Skeleton className="h-4 w-4/5" />
709
+ <Skeleton className="h-4 w-3/5" />
710
+ <Skeleton className="mt-stack ml-auto h-11 w-1/3 rounded-lg" />
711
+ <Skeleton className="h-4 w-2/3" />
712
+ </div>
713
+ ) : (
714
+ <>
715
+ {rows.map((row) =>
716
+ row.kind === 'activity' ? (
717
+ <ActivityRow
718
+ key={row.id}
719
+ steps={row.steps}
720
+ active={activeRun && row === lastRow}
721
+ />
722
+ ) : (
723
+ <MessageRow key={row.id} item={row} />
724
+ ),
725
+ )}
726
+ {pending && (
727
+ <ApprovalRow call={pending} deciding={working} onApprove={onApprove} onDecline={onDecline} />
728
+ )}
729
+ {status === 'waiting' && !activeRun && (
730
+ <div className="mb-2 flex items-center p-inset" data-testid="chat-panel-waiting">
731
+ <WorkingLabel label="Thinking" />
732
+ </div>
733
+ )}
734
+ {error && (
735
+ <ChatError message={error.message} onRetry={working || inCall ? undefined : onRetry} />
736
+ )}
737
+ {voice?.error && <ChatError message={voice.error.message} />}
738
+ </>
739
+ )}
740
+ </div>
741
+ </div>
742
+ <div
743
+ className={cn(
744
+ 'flex shrink-0 justify-center bg-background px-3 half:px-4',
745
+ !centred && 'sticky bottom-0 z-30 pb-3 half:pb-4',
746
+ )}
747
+ >
748
+ {!centred && (
749
+ <div className="pointer-events-none absolute inset-x-0 -top-10 h-10 bg-gradient-to-t from-background to-transparent" />
750
+ )}
751
+ <div className="w-full max-w-3xl">{composer}</div>
752
+ </div>
753
+ {centred && !inCall && emptyFooter && (
754
+ <div className="mx-auto mt-stack flex w-full max-w-3xl flex-col items-center px-3 half:px-4">
755
+ {emptyFooter}
756
+ </div>
757
+ )}
758
+ </div>
759
+ );
760
+ }