@tinyweb_dev/agent-framework-chat-ui 0.2.0 → 0.4.0

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 (101) hide show
  1. package/dist/components/Composer.d.ts +38 -0
  2. package/dist/components/Composer.d.ts.map +1 -0
  3. package/dist/components/Header.d.ts +7 -0
  4. package/dist/components/Header.d.ts.map +1 -0
  5. package/dist/components/Hero.d.ts +6 -0
  6. package/dist/components/Hero.d.ts.map +1 -0
  7. package/dist/components/RealtimeCallOverlay.d.ts +68 -0
  8. package/dist/components/RealtimeCallOverlay.d.ts.map +1 -0
  9. package/dist/components/RealtimeOrb.d.ts +21 -0
  10. package/dist/components/RealtimeOrb.d.ts.map +1 -0
  11. package/{src/components/Sidebar.tsx → dist/components/Sidebar.d.ts} +5 -9
  12. package/dist/components/Sidebar.d.ts.map +1 -0
  13. package/dist/components/TinywebChat.d.ts +3 -0
  14. package/dist/components/TinywebChat.d.ts.map +1 -0
  15. package/dist/components/Transcript.d.ts +20 -0
  16. package/dist/components/Transcript.d.ts.map +1 -0
  17. package/dist/components/WireOrbEffect.d.ts +17 -0
  18. package/dist/components/WireOrbEffect.d.ts.map +1 -0
  19. package/dist/components/condense/CondensePill.d.ts +11 -0
  20. package/dist/components/condense/CondensePill.d.ts.map +1 -0
  21. package/dist/components/messages/AssistantMessage.d.ts +10 -0
  22. package/dist/components/messages/AssistantMessage.d.ts.map +1 -0
  23. package/dist/components/messages/ErrorMessage.d.ts +7 -0
  24. package/dist/components/messages/ErrorMessage.d.ts.map +1 -0
  25. package/dist/components/messages/ToolMessage.d.ts +17 -0
  26. package/dist/components/messages/ToolMessage.d.ts.map +1 -0
  27. package/dist/components/messages/UserMessage.d.ts +7 -0
  28. package/dist/components/messages/UserMessage.d.ts.map +1 -0
  29. package/dist/components/tool/ExecRenderer.d.ts +14 -0
  30. package/dist/components/tool/ExecRenderer.d.ts.map +1 -0
  31. package/dist/components/tool/ImageRenderer.d.ts +16 -0
  32. package/dist/components/tool/ImageRenderer.d.ts.map +1 -0
  33. package/dist/components/tool/JsonRenderer.d.ts +11 -0
  34. package/dist/components/tool/JsonRenderer.d.ts.map +1 -0
  35. package/dist/components/tool/ToolCard.d.ts +29 -0
  36. package/dist/components/tool/ToolCard.d.ts.map +1 -0
  37. package/dist/components/tool/builtinRenderers.d.ts +9 -0
  38. package/dist/components/tool/builtinRenderers.d.ts.map +1 -0
  39. package/dist/hooks/useAgentChat.d.ts +46 -0
  40. package/dist/hooks/useAgentChat.d.ts.map +1 -0
  41. package/dist/hooks/useAnchorLatestUser.d.ts +15 -0
  42. package/dist/hooks/useAnchorLatestUser.d.ts.map +1 -0
  43. package/dist/hooks/useInitialScrollToEnd.d.ts +15 -0
  44. package/dist/hooks/useInitialScrollToEnd.d.ts.map +1 -0
  45. package/dist/hooks/useNdjsonStream.d.ts +11 -0
  46. package/dist/hooks/useNdjsonStream.d.ts.map +1 -0
  47. package/dist/hooks/useRealtimeCall.d.ts +112 -0
  48. package/dist/hooks/useRealtimeCall.d.ts.map +1 -0
  49. package/dist/index.cjs +3243 -0
  50. package/dist/index.cjs.map +1 -0
  51. package/dist/index.d.ts +20 -0
  52. package/dist/index.d.ts.map +1 -0
  53. package/dist/index.js +3209 -0
  54. package/dist/index.js.map +1 -0
  55. package/dist/markdown/render.d.ts +2 -0
  56. package/dist/markdown/render.d.ts.map +1 -0
  57. package/{src → dist}/styles.css +29 -0
  58. package/dist/types.d.ts +257 -0
  59. package/dist/types.d.ts.map +1 -0
  60. package/dist/util/attachments.d.ts +28 -0
  61. package/dist/util/attachments.d.ts.map +1 -0
  62. package/dist/util/escape.d.ts +2 -0
  63. package/dist/util/escape.d.ts.map +1 -0
  64. package/dist/util/theme.d.ts +13 -0
  65. package/dist/util/theme.d.ts.map +1 -0
  66. package/dist/util/tool-detect.d.ts +26 -0
  67. package/dist/util/tool-detect.d.ts.map +1 -0
  68. package/dist/util/tool-labels.d.ts +11 -0
  69. package/dist/util/tool-labels.d.ts.map +1 -0
  70. package/package.json +14 -14
  71. package/src/components/Composer.tsx +0 -267
  72. package/src/components/Header.tsx +0 -16
  73. package/src/components/Hero.tsx +0 -16
  74. package/src/components/RealtimeCallOverlay.tsx +0 -894
  75. package/src/components/RealtimeOrb.tsx +0 -388
  76. package/src/components/TinywebChat.tsx +0 -95
  77. package/src/components/Transcript.tsx +0 -146
  78. package/src/components/WireOrbEffect.tsx +0 -556
  79. package/src/components/condense/CondensePill.tsx +0 -77
  80. package/src/components/messages/AssistantMessage.tsx +0 -15
  81. package/src/components/messages/ErrorMessage.tsx +0 -12
  82. package/src/components/messages/ToolMessage.tsx +0 -49
  83. package/src/components/messages/UserMessage.tsx +0 -37
  84. package/src/components/tool/ExecRenderer.tsx +0 -71
  85. package/src/components/tool/ImageRenderer.tsx +0 -47
  86. package/src/components/tool/JsonRenderer.tsx +0 -24
  87. package/src/components/tool/ToolCard.tsx +0 -65
  88. package/src/components/tool/builtinRenderers.tsx +0 -456
  89. package/src/hooks/useAgentChat.ts +0 -454
  90. package/src/hooks/useAnchorLatestUser.ts +0 -99
  91. package/src/hooks/useInitialScrollToEnd.ts +0 -41
  92. package/src/hooks/useNdjsonStream.ts +0 -71
  93. package/src/hooks/useRealtimeCall.ts +0 -452
  94. package/src/index.ts +0 -45
  95. package/src/markdown/render.ts +0 -121
  96. package/src/types.ts +0 -241
  97. package/src/util/attachments.ts +0 -87
  98. package/src/util/escape.ts +0 -16
  99. package/src/util/theme.ts +0 -40
  100. package/src/util/tool-detect.ts +0 -65
  101. package/src/util/tool-labels.ts +0 -34
@@ -1,894 +0,0 @@
1
- "use client"
2
-
3
- // Inline voice-call panel for a realtime agent session.
4
- //
5
- // Plan 0014 §9 (lifecycle) + plan 0019 (halo orb + audio-reactive UI).
6
- //
7
- // Layout (top → bottom):
8
- //
9
- // ┌─────────────────────────────────────────┐
10
- // │ [ status pill ] │ aria-live=polite
11
- // │ │
12
- // │ ◉ halo orb │ reacts to analysers
13
- // │ │
14
- // │ How can I help you today? │ hero copy (configurable)
15
- // │ │
16
- // │ agent: … user: … tool: web_… │ subtle one-liner
17
- // │ │
18
- // │ [⌨] [🎙 FAB+ripple] [✕] │ bottom row
19
- // └─────────────────────────────────────────┘
20
- //
21
- // The keyboard icon (left) and the close icon (right) both call
22
- // `props.onClose()`. Per plan 0019 §7 a richer "compose text mid-call"
23
- // mode is out of scope; the keyboard button simply means "switch backı
24
- // to text mode" today.
25
-
26
- import { useCallback, useEffect, useMemo, useRef, useState } from "react"
27
- import { useRealtimeCall, type CallStatus, type ToolHandlerMap } from "../hooks/useRealtimeCall"
28
- import { Transcript } from "./Transcript"
29
- import { WireOrbEffect, type WireOrbState } from "./WireOrbEffect"
30
- import type { UseAgentChatReturn } from "../hooks/useAgentChat"
31
- import type { ToolRenderer, TranscriptNode } from "../types"
32
-
33
- /**
34
- * Status-pill label override keys. Beyond the lifecycle `CallStatus`
35
- * values, the `"active"` bucket has three rendered sub-states
36
- * (listening / speaking / muted). Consumers can override either the
37
- * whole `"active"` bucket or each sub-state individually.
38
- */
39
- export type RealtimeStatusLabelKey =
40
- | CallStatus
41
- | "active-listening"
42
- | "active-speaking"
43
- | "active-muted"
44
-
45
- export type RealtimeCallOverlayProps = {
46
- readonly tokenEndpoint: string
47
- readonly tokenHeaders?: HeadersInit
48
- readonly tokenBody?: Record<string, unknown> | (() => Record<string, unknown>)
49
- readonly toolHandlers?: ToolHandlerMap
50
- /** Server tool-proxy base (see RealtimeProp.toolProxyPath). */
51
- readonly toolProxyPath?: string
52
- readonly toolProxyHeaders?: HeadersInit
53
- readonly idleTimeoutMs?: number
54
- /** Close handler invoked on hangup or explicit dismiss. */
55
- readonly onClose: () => void
56
- /**
57
- * Friendly call label shown at the top (e.g. agent name). Optional.
58
- * Kept for backwards-compatibility; no longer rendered by default,
59
- * but consumers can read it via props if they re-skin.
60
- */
61
- readonly title?: string
62
- /**
63
- * Greeting line under the orb. Defaults to a short helpful prompt.
64
- * Pass an empty string to hide.
65
- */
66
- readonly hero?: string
67
- /**
68
- * Override the top status-pill text for i18n / branding.
69
- *
70
- * Keys map to `CallStatus` values, plus three richer sub-state keys
71
- * for the `"active"` bucket (`active-listening`, `active-speaking`,
72
- * `active-muted`). When a richer key is missing, the resolver falls
73
- * back to the bare `"active"` override, then to the built-in English
74
- * default.
75
- */
76
- readonly statusLabels?: Partial<Record<RealtimeStatusLabelKey, string>>
77
- /**
78
- * Chat handle from the host's `useAgentChat`. When provided the
79
- * overlay mirrors realtime events into the chat transcript so the
80
- * unified history covers both text and voice modes, and a developer
81
- * debug sidebar can render the live nodes on the right.
82
- */
83
- readonly chat?: UseAgentChatReturn
84
- /** Custom tool renderers reused inside the debug sidebar. */
85
- readonly toolRenderers?: ToolRenderer[]
86
- /**
87
- * Fired when the user's voice turn finishes transcribing. Hosts wire
88
- * this to their server-side persistence so a page reload reconstructs
89
- * the voice history. Skipped on empty / whitespace-only text. Errors
90
- * are caught and ignored — host is responsible for retry policy.
91
- */
92
- readonly onUserTurn?: (text: string) => void | Promise<void>
93
- /**
94
- * Fired when the agent's voice turn ends (`turn-complete` or
95
- * `agent-transcript-final`). The accumulated transcript for the turn
96
- * is passed verbatim. Skipped on empty turns. Errors are caught and
97
- * ignored — host is responsible for retry policy.
98
- */
99
- readonly onAssistantTurn?: (text: string) => void | Promise<void>
100
- }
101
-
102
- const DEFAULT_HERO = "How can I help you today?"
103
-
104
- const KeyboardIcon = () => (
105
- <svg
106
- viewBox="0 0 24 24"
107
- width="22"
108
- height="22"
109
- fill="none"
110
- stroke="currentColor"
111
- strokeWidth="1.6"
112
- strokeLinecap="round"
113
- strokeLinejoin="round"
114
- aria-hidden="true"
115
- >
116
- <rect x="2.5" y="6" width="19" height="12" rx="2" />
117
- <path d="M6.5 10h.01M10 10h.01M13.5 10h.01M17 10h.01M6.5 14h11" />
118
- </svg>
119
- )
120
-
121
- const MicIcon = () => (
122
- <svg
123
- viewBox="0 0 24 24"
124
- width="26"
125
- height="26"
126
- fill="none"
127
- stroke="currentColor"
128
- strokeWidth="1.8"
129
- strokeLinecap="round"
130
- strokeLinejoin="round"
131
- aria-hidden="true"
132
- >
133
- <rect x="9" y="3" width="6" height="12" rx="3" />
134
- <path d="M5 11a7 7 0 0 0 14 0" />
135
- <path d="M12 18v3" />
136
- </svg>
137
- )
138
-
139
- const MicOffIcon = () => (
140
- <svg
141
- viewBox="0 0 24 24"
142
- width="26"
143
- height="26"
144
- fill="none"
145
- stroke="currentColor"
146
- strokeWidth="1.8"
147
- strokeLinecap="round"
148
- strokeLinejoin="round"
149
- aria-hidden="true"
150
- >
151
- <path d="M3 3l18 18" />
152
- <path d="M9 9v3a3 3 0 0 0 5.12 2.12" />
153
- <path d="M15 11.34V6a3 3 0 0 0-6-.34" />
154
- <path d="M5 11a7 7 0 0 0 11.27 5.5" />
155
- <path d="M19 11a7 7 0 0 0-.18-1.59" />
156
- <path d="M12 18v3" />
157
- </svg>
158
- )
159
-
160
- const BugIcon = () => (
161
- <svg
162
- viewBox="0 0 24 24"
163
- width="18"
164
- height="18"
165
- fill="none"
166
- stroke="currentColor"
167
- strokeWidth="1.7"
168
- strokeLinecap="round"
169
- strokeLinejoin="round"
170
- aria-hidden="true"
171
- >
172
- <path d="M8 6a4 4 0 1 1 8 0" />
173
- <rect x="6" y="8" width="12" height="11" rx="5" />
174
- <path d="M12 19v-9M4 12h3M17 12h3M5 7l2 1M19 7l-2 1M5 17l2-1M19 17l-2-1" />
175
- </svg>
176
- )
177
-
178
- const ChevronUpIcon = () => (
179
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
180
- <polyline points="6 15 12 9 18 15" />
181
- </svg>
182
- )
183
-
184
- const ChevronDownIcon = () => (
185
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
186
- <polyline points="6 9 12 15 18 9" />
187
- </svg>
188
- )
189
-
190
- const CloseIcon = () => (
191
- <svg
192
- viewBox="0 0 24 24"
193
- width="22"
194
- height="22"
195
- fill="none"
196
- stroke="currentColor"
197
- strokeWidth="1.8"
198
- strokeLinecap="round"
199
- strokeLinejoin="round"
200
- aria-hidden="true"
201
- >
202
- <path d="M6 6l12 12M18 6L6 18" />
203
- </svg>
204
- )
205
-
206
- const resolveStatusLabel = (
207
- status: CallStatus,
208
- subState: "listening" | "speaking" | "muted" | null,
209
- overrides: Partial<Record<RealtimeStatusLabelKey, string>> | undefined,
210
- ): string => {
211
- if (status === "active" && subState !== null) {
212
- const richKey: RealtimeStatusLabelKey =
213
- subState === "listening"
214
- ? "active-listening"
215
- : subState === "speaking"
216
- ? "active-speaking"
217
- : "active-muted"
218
- const rich = overrides?.[richKey]
219
- if (rich) return rich
220
- const bucket = overrides?.active
221
- if (bucket) return bucket
222
- if (subState === "listening") return "I'm listening"
223
- if (subState === "speaking") return "Speaking…"
224
- return "Muted"
225
- }
226
- const override = overrides?.[status]
227
- if (override) return override
228
- if (status === "connecting") return "Connecting…"
229
- if (status === "ending") return "Ending…"
230
- if (status === "error") return "Error"
231
- if (status === "active") return "Connected"
232
- return "Idle"
233
- }
234
-
235
- /**
236
- * Compact two-column "recent turns" panel rendered inside the call
237
- * overlay. Shows the last few user / assistant exchanges so the call
238
- * does not feel like a memoryless single-line transcript, while the
239
- * orb itself stays the visual centerpiece.
240
- *
241
- * Layout:
242
- *
243
- * ┌──────────────────────────┬──────────────────────────┐
244
- * │ user · 3 turns ago │ assistant │
245
- * │ user · 2 turns ago │ assistant │
246
- * │ user · current (live) │ assistant (live) │
247
- * └──────────────────────────┴──────────────────────────┘
248
- *
249
- * Data source: `chat.nodes` (mirror of the unified text+voice
250
- * transcript) — falls back to just the live streaming lines when no
251
- * `chat` adapter is wired. Tool calls render as a small pill under
252
- * the assistant column.
253
- */
254
- type RealtimeRecentsProps = {
255
- readonly nodes: ReadonlyArray<TranscriptNode> | undefined
256
- readonly liveUser: string
257
- readonly liveAgent: string
258
- readonly lastToolCall: { name: string; args: Record<string, unknown> } | null
259
- readonly error: string | null
260
- }
261
-
262
- /** Max turn pairs (user+assistant) to display, including the live row. */
263
- const MAX_RECENT_TURNS = 5
264
-
265
- type RecentTurn = {
266
- readonly key: string
267
- readonly user: string | null
268
- readonly assistant: string | null
269
- readonly tool: { name: string; args: Record<string, unknown> } | null
270
- readonly live: boolean
271
- }
272
-
273
- /**
274
- * Walk the unified transcript nodes from the end backwards and pair
275
- * up assistant rows with the preceding user row. Tool calls get
276
- * attached to the assistant turn that owns them.
277
- */
278
- const buildRecentTurns = (nodes: ReadonlyArray<TranscriptNode> | undefined): RecentTurn[] => {
279
- if (!nodes || nodes.length === 0) return []
280
- const turns: RecentTurn[] = []
281
- let pendingAssistant: string | null = null
282
- let pendingTool: { name: string; args: Record<string, unknown> } | null = null
283
- for (let i = nodes.length - 1; i >= 0; i--) {
284
- const n = nodes[i]
285
- if (n.kind === "tool-call" && !pendingTool) {
286
- pendingTool = { name: n.name, args: (n.input as Record<string, unknown>) ?? {} }
287
- continue
288
- }
289
- if (n.kind === "assistant") {
290
- pendingAssistant = n.content
291
- continue
292
- }
293
- if (n.kind === "user") {
294
- turns.unshift({
295
- key: n.id,
296
- user: n.content,
297
- assistant: pendingAssistant,
298
- tool: pendingTool,
299
- live: false,
300
- })
301
- pendingAssistant = null
302
- pendingTool = null
303
- if (turns.length >= MAX_RECENT_TURNS) break
304
- continue
305
- }
306
- }
307
- // Leading assistant turn with no preceding user (rare — e.g. agent
308
- // greeting). Surface it so the user can still see the latest reply.
309
- if (pendingAssistant !== null && turns.length < MAX_RECENT_TURNS) {
310
- turns.unshift({
311
- key: `lead-${turns[0]?.key ?? "0"}`,
312
- user: null,
313
- assistant: pendingAssistant,
314
- tool: pendingTool,
315
- live: false,
316
- })
317
- }
318
- return turns
319
- }
320
-
321
- // localStorage key used to persist the recents panel collapse/expand state
322
- // across page reloads. SSR-safe: we only touch `window` inside the lazy
323
- // initializer and the post-mount sync effect.
324
- const RECENTS_EXPANDED_STORAGE_KEY = "tinyweb.realtime.recents.expanded"
325
-
326
- const RealtimeRecents = (props: RealtimeRecentsProps) => {
327
- // Default = compact (only the latest assistant line); expanded reveals
328
- // the full 2-column recent-turns panel so the user can scan back a few
329
- // exchanges without leaving the call surface.
330
- //
331
- // Persisted to localStorage so reloading the page keeps the user's
332
- // chosen collapse state. Lazy initializer guards against SSR (no
333
- // `window`) and malformed JSON.
334
- const [expanded, setExpanded] = useState<boolean>(() => {
335
- if (typeof window === "undefined") return false
336
- try {
337
- const raw = window.localStorage.getItem(RECENTS_EXPANDED_STORAGE_KEY)
338
- if (raw === null) return false
339
- return JSON.parse(raw) === true
340
- } catch {
341
- return false
342
- }
343
- })
344
-
345
- useEffect(() => {
346
- if (typeof window === "undefined") return
347
- try {
348
- window.localStorage.setItem(
349
- RECENTS_EXPANDED_STORAGE_KEY,
350
- JSON.stringify(expanded),
351
- )
352
- } catch {
353
- // localStorage may throw in private mode / when quota exceeded —
354
- // we intentionally swallow: persistence is best-effort UX, not
355
- // critical state.
356
- }
357
- }, [expanded])
358
- const turns = useMemo(() => buildRecentTurns(props.nodes), [props.nodes])
359
-
360
- // Build a synthetic "live" row from the in-flight streaming partials.
361
- // We only render it when the streamed text isn't already represented in
362
- // ANY recent committed turn — otherwise the live ribbon duplicates a
363
- // committed bubble (e.g. when the live state hasn't been cleared yet
364
- // after `turn-complete`, or when committed nodes arrive interleaved
365
- // with the still-populated live state).
366
- const liveUserNew =
367
- !!props.liveUser &&
368
- !turns.some((t) => t.user && t.user === props.liveUser)
369
- const liveAgentNew =
370
- !!props.liveAgent &&
371
- !turns.some((t) => t.assistant && t.assistant === props.liveAgent)
372
- const liveRow: RecentTurn | null =
373
- liveUserNew || liveAgentNew
374
- ? {
375
- key: "__live__",
376
- user: liveUserNew ? props.liveUser : null,
377
- assistant: liveAgentNew ? props.liveAgent : null,
378
- tool: props.lastToolCall,
379
- live: true,
380
- }
381
- : null
382
-
383
- const rows: RecentTurn[] = liveRow
384
- ? [...turns.slice(-(MAX_RECENT_TURNS - 1)), liveRow]
385
- : turns
386
-
387
- // Compact mode: surface only the latest agent utterance (committed or
388
- // live). Falls back to the user's last said line if the agent hasn't
389
- // replied yet, and finally to nothing.
390
- const latestRow = rows[rows.length - 1]
391
- const compactAgentLine = latestRow?.assistant ?? null
392
- const compactUserLine = latestRow?.user ?? null
393
- const compactTool = latestRow?.tool ?? null
394
- const compactLive = latestRow?.live ?? false
395
-
396
- const hasContent = rows.length > 0
397
- const showError = Boolean(props.error)
398
- // Only hide entirely when there is truly nothing to show AND the user
399
- // has not opted into the expanded surface. If `expanded === true` is
400
- // persisted from a previous session, we still render the container
401
- // (with the toggle) so the saved preference is visible immediately on
402
- // a fresh conversation — no need to wait for the first turn to land.
403
- if (!hasContent && !showError && !expanded) return null
404
-
405
- // Render the toggle whenever the surface is visible: with content, in
406
- // error state, or when the user has the panel pinned open. This lets
407
- // the user collapse the empty expanded surface back down if desired.
408
- const toggleBtn =
409
- hasContent || expanded ? (
410
- <button
411
- type="button"
412
- className="realtime-recents-toggle"
413
- aria-label={expanded ? "Collapse transcript" : "Expand transcript"}
414
- aria-expanded={expanded}
415
- title={expanded ? "Collapse" : "Expand to see recent turns"}
416
- onClick={() => setExpanded((v) => !v)}
417
- >
418
- {expanded ? <ChevronDownIcon /> : <ChevronUpIcon />}
419
- </button>
420
- ) : null
421
-
422
- return (
423
- <div
424
- className={`realtime-recents${expanded ? " is-expanded" : " is-compact"}`}
425
- aria-label="Recent conversation"
426
- >
427
- {toggleBtn}
428
-
429
- {expanded ? (
430
- <div className="realtime-recents-list">
431
- {rows.map((t) => (
432
- <div
433
- key={t.key}
434
- className={`realtime-recent-turn${t.live ? " is-live" : ""}`}
435
- >
436
- {t.user ? (
437
- <div className="realtime-recent-row realtime-recent-row--user">
438
- <span className="realtime-recent-bubble realtime-recent-bubble--user">
439
- {t.user}
440
- </span>
441
- </div>
442
- ) : null}
443
- {t.assistant ? (
444
- <div className="realtime-recent-row realtime-recent-row--agent">
445
- <span className="realtime-recent-bubble realtime-recent-bubble--agent">
446
- {t.assistant}
447
- </span>
448
- </div>
449
- ) : null}
450
- {t.tool ? (
451
- <div className="realtime-recent-row realtime-recent-row--agent">
452
- <span
453
- className="realtime-recent-tool"
454
- title={JSON.stringify(t.tool.args)}
455
- >
456
- <span className="realtime-recent-tool-dot" aria-hidden="true" />
457
- {t.tool.name}
458
- </span>
459
- </div>
460
- ) : null}
461
- </div>
462
- ))}
463
- </div>
464
- ) : (
465
- <div className={`realtime-recents-compact${compactLive ? " is-live" : ""}`}>
466
- {compactAgentLine ? (
467
- <p className="realtime-recents-compact-line realtime-recents-compact-line--agent">
468
- {compactAgentLine}
469
- </p>
470
- ) : compactUserLine ? (
471
- <p className="realtime-recents-compact-line realtime-recents-compact-line--user">
472
- {compactUserLine}
473
- </p>
474
- ) : null}
475
- {compactTool ? (
476
- <span
477
- className="realtime-recent-tool"
478
- title={JSON.stringify(compactTool.args)}
479
- >
480
- <span className="realtime-recent-tool-dot" aria-hidden="true" />
481
- {compactTool.name}
482
- </span>
483
- ) : null}
484
- </div>
485
- )}
486
-
487
- {showError ? (
488
- <div className="realtime-recent-error" role="alert">
489
- {props.error}
490
- </div>
491
- ) : null}
492
- </div>
493
- )
494
- }
495
-
496
- export const RealtimeCallOverlay = (props: RealtimeCallOverlayProps) => {
497
- const chat = props.chat
498
- // Bridge realtime events → chat transcript so the unified history
499
- // (and the developer debug sidebar) shows voice turns the same way
500
- // text turns are rendered. Stable per-turn cursor: each new agent
501
- // turn opens one assistant row by emitting `text-delta` deltas, and
502
- // `turn-complete` closes it with `text-end`. Tool calls flow through
503
- // the standard `tool-call` / `tool-result` events so existing tool
504
- // renderers light up unchanged.
505
- // Accumulate agent transcript across deltas so we can fire
506
- // `onAssistantTurn` with the full turn text on `turn-complete` /
507
- // `agent-transcript-final`. Reset on each turn boundary.
508
- const agentTurnRef = useRef("")
509
- const onUserTurnRef = useRef(props.onUserTurn)
510
- const onAssistantTurnRef = useRef(props.onAssistantTurn)
511
- onUserTurnRef.current = props.onUserTurn
512
- onAssistantTurnRef.current = props.onAssistantTurn
513
-
514
- const flushAssistantTurn = useCallback(() => {
515
- const text = agentTurnRef.current
516
- agentTurnRef.current = ""
517
- if (!text) return
518
- const cb = onAssistantTurnRef.current
519
- if (!cb) return
520
- // Swallow handler errors — persistence retry is the host's problem.
521
- try {
522
- const r = cb(text)
523
- if (r && typeof (r as Promise<unknown>).catch === "function") {
524
- ;(r as Promise<unknown>).catch(() => {})
525
- }
526
- } catch {
527
- // ignore
528
- }
529
- }, [])
530
-
531
- const fireUserTurn = useCallback((text: string) => {
532
- const trimmed = text.trim()
533
- if (!trimmed) return
534
- const cb = onUserTurnRef.current
535
- if (!cb) return
536
- try {
537
- const r = cb(trimmed)
538
- if (r && typeof (r as Promise<unknown>).catch === "function") {
539
- ;(r as Promise<unknown>).catch(() => {})
540
- }
541
- } catch {
542
- // ignore
543
- }
544
- }, [])
545
-
546
- const onRealtimeEvent = useCallback(
547
- (event: import("@tinyweb-agent-framework/realtime/events").RealtimeEvent) => {
548
- switch (event.type) {
549
- case "user-transcript-final":
550
- if (event.text.trim()) {
551
- chat?.appendUserMessage(event.text)
552
- fireUserTurn(event.text)
553
- }
554
- return
555
- case "agent-transcript-delta":
556
- // Defensive turn-boundary guard: Gemini Live can chain a new
557
- // agent turn WITHOUT emitting an explicit `agent-transcript-final`
558
- // or `turn-complete` between them. When the previous turn was
559
- // flushed, `agentTurnRef.current` is empty — that's a clean
560
- // signal this delta starts a FRESH turn. Close any lingering
561
- // open assistant cursor first so this delta opens a NEW
562
- // assistant node instead of concatenating into the previous
563
- // bubble.
564
- if (agentTurnRef.current === "") {
565
- chat?.applyEvent({ type: "text-end" })
566
- }
567
- agentTurnRef.current += event.text
568
- chat?.applyEvent({ type: "text-delta", text: event.text })
569
- return
570
- case "agent-transcript-final":
571
- // session.ts now accumulates fragments and emits the FULL
572
- // turn text on `agent-transcript-final`. If deltas already
573
- // streamed the same content (agentTurnRef.current non-empty),
574
- // re-applying a text-delta here would commit a SECOND
575
- // duplicate assistant bubble into chat.nodes (since the
576
- // following text-end closes that fresh streaming node).
577
- // Only synthesize a delta when the provider emitted `final`
578
- // without streaming any deltas first.
579
- if (event.text && !agentTurnRef.current) {
580
- agentTurnRef.current = event.text
581
- chat?.applyEvent({ type: "text-delta", text: event.text })
582
- }
583
- chat?.applyEvent({ type: "text-end" })
584
- flushAssistantTurn()
585
- return
586
- case "turn-complete":
587
- chat?.applyEvent({ type: "text-end" })
588
- flushAssistantTurn()
589
- return
590
- case "tool-call":
591
- chat?.applyEvent({
592
- type: "tool-call",
593
- id: event.id,
594
- name: event.name,
595
- input: event.args,
596
- })
597
- return
598
- case "tool-result":
599
- chat?.applyEvent({
600
- type: "tool-result",
601
- id: event.id,
602
- name: event.name,
603
- result: event.result,
604
- })
605
- return
606
- case "tool-error":
607
- chat?.applyEvent({
608
- type: "tool-error",
609
- id: event.id,
610
- name: event.name,
611
- message: event.message,
612
- })
613
- return
614
- default:
615
- return
616
- }
617
- },
618
- [chat],
619
- )
620
-
621
- // CROSS-CALL MEMORY.
622
- // When the user hangs up and re-opens the call, Gemini Live spins up a
623
- // brand-new session — meaning zero memory of anything said in the prior
624
- // call (or anything typed via text in `chat.nodes`). To match the
625
- // "feels like a continuous conversation" UX that text LLM chats get for
626
- // free (they replay the full message list on every request), we hand
627
- // the prior user+assistant text turns to the realtime session at
628
- // startup. The realtime client embeds them into `systemInstruction`
629
- // inside the setup frame (see `buildSetupFrame` /
630
- // `buildHistoryTranscript` in `packages/realtime/src/client/session.ts`).
631
- //
632
- // We deliberately pass a THUNK rather than a memoized array. start()
633
- // runs once on mount; the thunk is invoked exactly then and captures
634
- // the freshest `chat.nodes` snapshot. Using a value here would either
635
- // race (stale closure) or re-create the hook every time a node was
636
- // appended during the call.
637
- const chatNodesRef = useRef<ReadonlyArray<TranscriptNode> | undefined>(undefined)
638
- chatNodesRef.current = chat?.nodes
639
- const getInitialHistory = useCallback(() => {
640
- const nodes = chatNodesRef.current
641
- if (!nodes || nodes.length === 0) return undefined
642
- const turns: Array<{ role: "user" | "model"; text: string }> = []
643
- for (const n of nodes) {
644
- // Defensive: chat.nodes content can be markdown, MDX, or carry
645
- // tool-call JSON artifacts; coerce to a plain string and trim.
646
- // Anything non-string / empty after trim is skipped.
647
- if (n.kind === "user" || n.kind === "assistant") {
648
- const raw = n.content
649
- const text = typeof raw === "string" ? raw.trim() : String(raw ?? "").trim()
650
- if (!text) continue
651
- turns.push({ role: n.kind === "user" ? "user" : "model", text })
652
- }
653
- // Skip tool-call / tool-result / tool-error / error / condense —
654
- // they don't translate cleanly to Gemini Live turns and would
655
- // confuse role alternation.
656
- }
657
- return turns.length > 0 ? turns : undefined
658
- }, [])
659
-
660
- const call = useRealtimeCall({
661
- tokenEndpoint: props.tokenEndpoint,
662
- tokenHeaders: props.tokenHeaders,
663
- tokenBody: props.tokenBody,
664
- toolHandlers: props.toolHandlers,
665
- toolProxyPath: props.toolProxyPath,
666
- toolProxyHeaders: props.toolProxyHeaders,
667
- idleTimeoutMs: props.idleTimeoutMs,
668
- onEvent: onRealtimeEvent,
669
- initialHistory: getInitialHistory,
670
- })
671
-
672
- // Debug sidebar visibility. Off by default; toggled via the bug icon
673
- // in the footer. Only available when a `chat` handle is wired.
674
- const [debugOpen, setDebugOpen] = useState(false)
675
-
676
- // Auto-start the call once on mount. The panel is mounted by a user
677
- // gesture (button click) so `getUserMedia` / `AudioContext.resume`
678
- // are within the permitted gesture window.
679
- //
680
- // StrictMode in Next dev double-mounts the component. The first
681
- // mount's start() races against the unmount: cleanup() in the hook
682
- // flips `cancelledRef`, so the in-flight start() swallows the
683
- // freshly-opened session instead of leaking it. The second mount
684
- // then starts a clean attempt that actually reaches "active".
685
- useEffect(() => {
686
- void call.start()
687
- // Intentionally empty deps — start exactly once per mount.
688
- // eslint-disable-next-line react-hooks/exhaustive-deps
689
- }, [])
690
-
691
- // ESC to hang up.
692
- useEffect(() => {
693
- const onKey = async (e: KeyboardEvent) => {
694
- if (e.key === "Escape") {
695
- await call.hangup()
696
- props.onClose()
697
- }
698
- }
699
- window.addEventListener("keydown", onKey)
700
- return () => window.removeEventListener("keydown", onKey)
701
- }, [call, props])
702
-
703
- const handleHangup = async () => {
704
- await call.hangup()
705
- props.onClose()
706
- }
707
-
708
- // Speaking detection: the agentTranscript persists across turns
709
- // (last reply stays visible), so it's a poor signal for "is the
710
- // agent currently producing audio". We instead sample the output
711
- // analyser at ~10Hz and flip a boolean when RMS energy crosses a
712
- // small threshold. This naturally clears once the agent stops
713
- // playing audio, even though the transcript ribbon remains.
714
- const [agentSpeaking, setAgentSpeaking] = useState(false)
715
- useEffect(() => {
716
- const analyser = call.outputAnalyser
717
- if (!analyser || call.status !== "active") {
718
- setAgentSpeaking(false)
719
- return
720
- }
721
- const buf = new Uint8Array(analyser.frequencyBinCount)
722
- let raf = 0
723
- let lastActiveAt = 0
724
- const tick = () => {
725
- analyser.getByteFrequencyData(buf)
726
- const half = buf.length >> 1
727
- let sum = 0
728
- for (let i = 0; i < half; i++) sum += buf[i] ?? 0
729
- const avg = sum / (half * 255)
730
- const now = performance.now()
731
- if (avg > 0.02) {
732
- lastActiveAt = now
733
- setAgentSpeaking(true)
734
- } else if (now - lastActiveAt > 350) {
735
- // Hold for a short tail so brief silences between phonemes
736
- // don't flicker the label.
737
- setAgentSpeaking(false)
738
- }
739
- raf = requestAnimationFrame(tick)
740
- }
741
- raf = requestAnimationFrame(tick)
742
- return () => cancelAnimationFrame(raf)
743
- }, [call.outputAnalyser, call.status])
744
-
745
- // Lifecycle → orb visual state. Maps the call's `CallStatus` onto the
746
- // 5-state machine the wireframe-orb shader understands (`idle`,
747
- // `listening`, `thinking`, `speaking`, `connecting`).
748
- //
749
- // Priority while `active`:
750
- // 1. `toolRunning` → `thinking` (model paused waiting on a tool result;
751
- // shown as amber spiral-orbit dust regardless of mic mute / audio).
752
- // 2. `muted` → `idle` (mic closed; orb falls back to ambient idle look
753
- // so the visual matches the muted intent).
754
- // 3. `agentSpeaking` → `speaking` (FFT detected agent audio).
755
- // 4. otherwise → `listening` (mic open, no agent audio).
756
- const orbState: WireOrbState =
757
- call.status === "active"
758
- ? call.toolRunning
759
- ? "thinking"
760
- : call.muted
761
- ? "idle"
762
- : agentSpeaking
763
- ? "speaking"
764
- : "listening"
765
- : call.status === "connecting"
766
- ? "connecting"
767
- : "idle"
768
-
769
- // Status-pill sub-state for the "active" bucket.
770
- const subState: "listening" | "speaking" | "muted" | null =
771
- call.status === "active"
772
- ? call.muted
773
- ? "muted"
774
- : agentSpeaking
775
- ? "speaking"
776
- : "listening"
777
- : null
778
-
779
- const statusLabel = resolveStatusLabel(call.status, subState, props.statusLabels)
780
- const hero = props.hero === undefined ? DEFAULT_HERO : props.hero
781
- const rippleActive = call.status === "active" && !call.muted
782
-
783
- const showDebug = Boolean(chat) && debugOpen
784
- return (
785
- <div
786
- className={`realtime-stage-wrap${showDebug ? " realtime-stage-wrap--debug" : ""}`}
787
- >
788
- <section
789
- className="realtime-inline-panel realtime-inline-panel--wire"
790
- aria-label="Realtime call"
791
- >
792
- {/* Full-bleed wireframe orb backdrop. Sits behind all controls
793
- * so the dust halo can extend past the visible panel bounds. */}
794
- <div className="realtime-orb-wrap realtime-orb-wrap--wire">
795
- <WireOrbEffect
796
- state={orbState}
797
- levelRef={call.levelRef}
798
- inputAnalyser={call.inputAnalyser}
799
- outputAnalyser={call.outputAnalyser}
800
- />
801
- </div>
802
-
803
- <div
804
- className={`realtime-status realtime-status-${call.status}`}
805
- role="status"
806
- aria-live="polite"
807
- >
808
- {statusLabel}
809
- </div>
810
-
811
- {/* Spacer that used to host the orb — keeps the vertical rhythm
812
- * (status pill at top, transcript+footer at bottom) intact. */}
813
- <div className="realtime-stage realtime-stage--wire" aria-hidden="true" />
814
-
815
- {hero ? <p className="realtime-hero">{hero}</p> : null}
816
-
817
- <RealtimeRecents
818
- nodes={chat?.nodes}
819
- liveUser={call.userTranscript}
820
- liveAgent={call.agentTranscript}
821
- lastToolCall={call.lastToolCall}
822
- error={call.error}
823
- />
824
-
825
- <footer className="realtime-inline-footer">
826
- <button
827
- type="button"
828
- className="realtime-icon-btn"
829
- aria-label="Switch to text"
830
- title="Switch to text"
831
- onClick={handleHangup}
832
- >
833
- <KeyboardIcon />
834
- </button>
835
-
836
- <div
837
- className="realtime-mic-stack"
838
- data-active={rippleActive ? "true" : "false"}
839
- >
840
- <span className="realtime-mic-ripple realtime-mic-ripple--1" aria-hidden="true" />
841
- <span className="realtime-mic-ripple realtime-mic-ripple--2" aria-hidden="true" />
842
- <span className="realtime-mic-ripple realtime-mic-ripple--3" aria-hidden="true" />
843
- <button
844
- type="button"
845
- className="realtime-mic-fab"
846
- aria-label={call.muted ? "Unmute microphone" : "Mute microphone"}
847
- aria-pressed={call.muted}
848
- title={call.muted ? "Unmute" : "Mute"}
849
- onClick={() => call.setMuted(!call.muted)}
850
- disabled={call.status !== "active"}
851
- >
852
- {call.muted ? <MicOffIcon /> : <MicIcon />}
853
- </button>
854
- </div>
855
-
856
- <button
857
- type="button"
858
- className="realtime-icon-btn realtime-icon-btn--close"
859
- aria-label="Hang up"
860
- title="Hang up"
861
- onClick={handleHangup}
862
- >
863
- <CloseIcon />
864
- </button>
865
- </footer>
866
-
867
- {chat ? (
868
- <button
869
- type="button"
870
- className={`realtime-debug-toggle${showDebug ? " is-open" : ""}`}
871
- aria-label={showDebug ? "Hide debug log" : "Show debug log"}
872
- aria-pressed={showDebug}
873
- title={showDebug ? "Hide debug log" : "Show debug log"}
874
- onClick={() => setDebugOpen((v) => !v)}
875
- >
876
- <BugIcon />
877
- </button>
878
- ) : null}
879
- </section>
880
-
881
- {showDebug && chat ? (
882
- <aside className="realtime-debug-side" aria-label="Realtime debug log">
883
- <div className="realtime-debug-head">Debug log</div>
884
- <Transcript
885
- nodes={chat.nodes}
886
- hero={{}}
887
- toolRenderers={props.toolRenderers}
888
- status={chat.status}
889
- />
890
- </aside>
891
- ) : null}
892
- </div>
893
- )
894
- }