@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,452 +0,0 @@
1
- "use client"
2
-
3
- // React hook wrapping `@tinyweb-agent-framework/realtime`'s
4
- // `connectRealtimeSession` for the chat-ui shell.
5
- //
6
- // Plan 0014 §9.
7
- //
8
- // Why a dedicated hook (rather than letting consumers wire raw
9
- // `connectRealtimeSession` themselves):
10
- // - We need React state for the transcript ribbons so the overlay
11
- // re-renders as deltas arrive.
12
- // - Lifecycle is fiddly: getUserMedia → AudioContext.resume() →
13
- // connect → events → unmount/cleanup. Easier as a hook.
14
- // - Multiple consumers (chat-ui's `RealtimeCallOverlay`, demos in
15
- // `examples/*`) all want the same state machine.
16
-
17
- import { useCallback, useEffect, useRef, useState } from "react"
18
- import {
19
- connectRealtimeSession,
20
- type RealtimeSession,
21
- type TokenEndpointResponse,
22
- } from "@tinyweb-agent-framework/realtime/client"
23
- import type { RealtimeEvent } from "@tinyweb-agent-framework/realtime/events"
24
-
25
- /**
26
- * Lifecycle phase of the call. Mirrors what the overlay renders.
27
- */
28
- export type CallStatus =
29
- | "idle"
30
- | "connecting"
31
- | "active"
32
- | "ending"
33
- | "error"
34
-
35
- /** Tool name → async handler. Runs in browser; no secrets. */
36
- export type ToolHandlerMap = Record<string, (args: Record<string, unknown>) => Promise<unknown>>
37
-
38
- export type UseRealtimeCallOptions = {
39
- /**
40
- * POST endpoint that mints ephemeral tokens. Response must match
41
- * [`TokenEndpointResponse`](../../../realtime/src/client/session.ts).
42
- * Endpoint is responsible for auth (Bearer / cookie). Optional
43
- * `body` is merged into the POST body so the host can scope tokens
44
- * to e.g. an agentId or sessionId.
45
- */
46
- readonly tokenEndpoint: string
47
- readonly tokenHeaders?: HeadersInit
48
- readonly tokenBody?: Record<string, unknown> | (() => Record<string, unknown>)
49
- /**
50
- * Per-tool client handlers. Use this only for tools that are safe to
51
- * execute in the browser with no server secrets (e.g. `time_now`, or
52
- * a pure JS calculator). Most useful tools need server access and
53
- * should go through `toolProxyPath` instead.
54
- */
55
- readonly toolHandlers?: ToolHandlerMap
56
- /**
57
- * Optional base path for a server tool proxy (e.g. `/api/tools`). When
58
- * set, any `tool-call` whose name is NOT covered by `toolHandlers`
59
- * falls back to `POST {toolProxyPath}/{name}` with the call args as
60
- * JSON. Server is expected to execute the tool and return the JSON
61
- * result. Use [`serverExecuteTool`](../../../realtime/src/tools/server.ts:1)
62
- * to implement the route.
63
- *
64
- * Combine with `toolHandlers` to override specific tools client-side
65
- * while letting everything else go through the server proxy.
66
- */
67
- readonly toolProxyPath?: string
68
- /** Optional headers (auth cookie / Bearer) forwarded to the proxy. */
69
- readonly toolProxyHeaders?: HeadersInit
70
- /**
71
- * Idle hang-up timeout. Default 10 minutes. The hook only resets the
72
- * idle timer on inbound events — silent calls eventually drop.
73
- */
74
- readonly idleTimeoutMs?: number
75
- /** Fires once per event. Useful for analytics / extra side effects. */
76
- readonly onEvent?: (event: RealtimeEvent) => void
77
- /**
78
- * Prior conversation history to replay into the new Gemini Live
79
- * session at startup. Closes the "agent forgets everything when I
80
- * hang up and call again" gap — without it each new call is a clean
81
- * slate, since a new WebSocket = a new server-side session.
82
- *
83
- * Pass an array (or a thunk returning one) of `{role, text}` pairs.
84
- * `role` is `"user"` for the human's turns and `"model"` for the
85
- * agent's prior replies (Gemini's vocabulary, NOT `"assistant"`).
86
- *
87
- * Resolved once per `start()` call so consumers can lazily derive
88
- * from a chat store without re-creating the hook on every node
89
- * append.
90
- */
91
- readonly initialHistory?:
92
- | ReadonlyArray<{ readonly role: "user" | "model"; readonly text: string }>
93
- | (() =>
94
- | ReadonlyArray<{ readonly role: "user" | "model"; readonly text: string }>
95
- | undefined)
96
- }
97
-
98
- export type UseRealtimeCallReturn = {
99
- readonly status: CallStatus
100
- readonly error: string | null
101
- /** Streaming partial transcript of the local user. */
102
- readonly userTranscript: string
103
- /** Streaming partial transcript of the agent. */
104
- readonly agentTranscript: string
105
- /** Most recent tool call (for UI display). Cleared on next call. */
106
- readonly lastToolCall: { name: string; args: Record<string, unknown> } | null
107
- /**
108
- * True while a client-side tool is executing (between `tool-call` and
109
- * `tool-result`/`tool-error`). UI uses this to switch the orb into the
110
- * `thinking` visual state — audio output is suspended while the model
111
- * waits for the tool response.
112
- */
113
- readonly toolRunning: boolean
114
- /** True when the user has muted their mic locally. */
115
- readonly muted: boolean
116
- readonly start: () => Promise<void>
117
- readonly hangup: () => Promise<void>
118
- readonly setMuted: (muted: boolean) => void
119
- /**
120
- * Mutable ref holding the latest audio level (0..1). Updated each
121
- * animation frame from a Web Audio analyser. Reads max(agent, user)
122
- * — useful for visualizations that just need "something is happening".
123
- * Stays at 0 outside an active call. Consumers read via `.current`.
124
- */
125
- readonly levelRef: { current: number }
126
- /**
127
- * Live analyser node on the agent output. `null` until the session
128
- * is `active`. Consumers needing FFT detail (e.g. 3D shader noise)
129
- * can call `getByteFrequencyData()` on this directly.
130
- */
131
- readonly outputAnalyser: AnalyserNode | null
132
- /** Live analyser node on the local mic input. */
133
- readonly inputAnalyser: AnalyserNode | null
134
- }
135
-
136
- const DEFAULT_IDLE_MS = 10 * 60 * 1000
137
-
138
- export const useRealtimeCall = (
139
- options: UseRealtimeCallOptions,
140
- ): UseRealtimeCallReturn => {
141
- const [status, setStatus] = useState<CallStatus>("idle")
142
- const [error, setError] = useState<string | null>(null)
143
- const [userTranscript, setUserTranscript] = useState("")
144
- const [agentTranscript, setAgentTranscript] = useState("")
145
- const [lastToolCall, setLastToolCall] = useState<
146
- { name: string; args: Record<string, unknown> } | null
147
- >(null)
148
- const [toolRunning, setToolRunning] = useState(false)
149
- const [muted, setMutedState] = useState(false)
150
-
151
- const sessionRef = useRef<RealtimeSession | null>(null)
152
- const audioCtxRef = useRef<AudioContext | null>(null)
153
- const micStreamRef = useRef<MediaStream | null>(null)
154
- const idleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
155
- // Tracks whether the in-flight start() should still commit its
156
- // results. Flipped to true by cleanup() so a start() racing past an
157
- // unmount (or a duplicated StrictMode mount) can detect it and tear
158
- // down the resources it acquired instead of leaking them.
159
- const cancelledRef = useRef(false)
160
- const idleMs = options.idleTimeoutMs ?? DEFAULT_IDLE_MS
161
-
162
- // Reactive audio level for visualization. We deliberately use a ref +
163
- // requestAnimationFrame loop instead of React state to avoid 60 fps
164
- // re-renders. Consumers (e.g. RealtimeOrb) read `levelRef.current`
165
- // inside `useFrame` so the value stays mutable per-frame.
166
- const levelRef = useRef<number>(0)
167
- const rafRef = useRef<number | null>(null)
168
- const [outputAnalyser, setOutputAnalyser] = useState<AnalyserNode | null>(null)
169
- const [inputAnalyser, setInputAnalyser] = useState<AnalyserNode | null>(null)
170
-
171
- const cleanup = useCallback(async () => {
172
- cancelledRef.current = true
173
- if (idleTimerRef.current) {
174
- clearTimeout(idleTimerRef.current)
175
- idleTimerRef.current = null
176
- }
177
- if (rafRef.current !== null) {
178
- cancelAnimationFrame(rafRef.current)
179
- rafRef.current = null
180
- }
181
- levelRef.current = 0
182
- setOutputAnalyser(null)
183
- setInputAnalyser(null)
184
- const session = sessionRef.current
185
- sessionRef.current = null
186
- if (session) await session.close().catch(() => undefined)
187
-
188
- const micStream = micStreamRef.current
189
- micStreamRef.current = null
190
- if (micStream) {
191
- micStream.getTracks().forEach((t) => t.stop())
192
- }
193
-
194
- const ctx = audioCtxRef.current
195
- audioCtxRef.current = null
196
- if (ctx && ctx.state !== "closed") {
197
- await ctx.close().catch(() => undefined)
198
- }
199
- }, [])
200
-
201
- const resetIdleTimer = useCallback(() => {
202
- if (idleTimerRef.current) clearTimeout(idleTimerRef.current)
203
- idleTimerRef.current = setTimeout(() => {
204
- setStatus("ending")
205
- void cleanup().then(() => setStatus("idle"))
206
- }, idleMs)
207
- }, [cleanup, idleMs])
208
-
209
- const start = useCallback(async () => {
210
- if (status === "connecting" || status === "active") return
211
- cancelledRef.current = false
212
- setError(null)
213
- setUserTranscript("")
214
- setAgentTranscript("")
215
- setLastToolCall(null)
216
- setToolRunning(false)
217
- setStatus("connecting")
218
-
219
- // 1. Mic permission.
220
- const micStream = await navigator.mediaDevices
221
- .getUserMedia({
222
- audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },
223
- })
224
- .catch((err: unknown) => {
225
- const msg = err instanceof Error ? err.message : String(err)
226
- setError(`mic permission denied: ${msg}`)
227
- setStatus("error")
228
- return null
229
- })
230
- if (!micStream) return
231
- if (cancelledRef.current) {
232
- micStream.getTracks().forEach((t) => t.stop())
233
- return
234
- }
235
- micStreamRef.current = micStream
236
-
237
- // 2. AudioContext. Some browsers require a user gesture before
238
- // resume(); the hook is invoked from a button click so we have one.
239
- const audioCtx = new AudioContext()
240
- audioCtxRef.current = audioCtx
241
- if (audioCtx.state === "suspended") {
242
- await audioCtx.resume().catch(() => undefined)
243
- }
244
- if (cancelledRef.current) {
245
- await cleanup()
246
- return
247
- }
248
-
249
- // 3. Open the session.
250
- const body =
251
- typeof options.tokenBody === "function" ? options.tokenBody() : options.tokenBody
252
- const handlerMap = new Map<string, (args: Record<string, unknown>) => Promise<unknown>>()
253
- if (options.toolHandlers) {
254
- for (const [k, v] of Object.entries(options.toolHandlers)) {
255
- handlerMap.set(k, v)
256
- }
257
- }
258
-
259
- // When `toolProxyPath` is configured, build a generic fallback that
260
- // forwards unknown tool calls to the server route. This is the
261
- // standard pattern for tools needing server secrets (web search,
262
- // VN gold scraper, perplexity, etc.) — see
263
- // [`serverExecuteTool`](../../../realtime/src/tools/server.ts:1).
264
- const proxyPath = options.toolProxyPath
265
- const proxyHeaders = options.toolProxyHeaders
266
- const fallbackToolHandler = proxyPath
267
- ? async (name: string, args: Record<string, unknown>) => {
268
- // Encode name segment to avoid traversal / double-slashes.
269
- const url = `${proxyPath.replace(/\/+$/, "")}/${encodeURIComponent(name)}`
270
- const res = await fetch(url, {
271
- method: "POST",
272
- headers: { "content-type": "application/json", ...(proxyHeaders ?? {}) },
273
- body: JSON.stringify(args),
274
- })
275
- if (!res.ok) {
276
- const text = await res.text().catch(() => res.statusText)
277
- throw new Error(`tool proxy ${name} ${res.status}: ${text}`)
278
- }
279
- return (await res.json()) as unknown
280
- }
281
- : undefined
282
-
283
- // Resolve history (supports thunk so callers can read fresh chat
284
- // state at call-start, not at hook-construction time).
285
- const initialHistory =
286
- typeof options.initialHistory === "function"
287
- ? options.initialHistory()
288
- : options.initialHistory
289
-
290
- const session = await connectRealtimeSession({
291
- tokenEndpoint: options.tokenEndpoint,
292
- headers: options.tokenHeaders,
293
- body,
294
- micStream,
295
- audioContext: audioCtx,
296
- toolHandlers: handlerMap,
297
- fallbackToolHandler,
298
- initialHistory,
299
- }).catch((err: unknown) => {
300
- const msg = err instanceof Error ? err.message : String(err)
301
- setError(`session failed: ${msg}`)
302
- setStatus("error")
303
- return null
304
- })
305
- if (!session) {
306
- await cleanup()
307
- return
308
- }
309
- // If the host unmounted (or hangup() was called) while we were
310
- // waiting on the network, swallow the freshly-opened session so
311
- // resources don't leak.
312
- if (cancelledRef.current) {
313
- await session.close().catch(() => undefined)
314
- await cleanup()
315
- return
316
- }
317
-
318
- sessionRef.current = session
319
- setStatus("active")
320
- resetIdleTimer()
321
-
322
- // Wire analyser-driven level tracking. Refs are exposed so 3D
323
- // canvases can read max(agent, user) each frame without re-render.
324
- setOutputAnalyser(session.outputAnalyser)
325
- setInputAnalyser(session.inputAnalyser)
326
- const outBuf = new Uint8Array(session.outputAnalyser.frequencyBinCount)
327
- const inBuf = new Uint8Array(session.inputAnalyser.frequencyBinCount)
328
- const tick = () => {
329
- session.outputAnalyser.getByteFrequencyData(outBuf)
330
- session.inputAnalyser.getByteFrequencyData(inBuf)
331
- // RMS-ish: average normalized energy in lower half (voice band).
332
- const half = outBuf.length >> 1
333
- let outSum = 0
334
- let inSum = 0
335
- for (let i = 0; i < half; i++) {
336
- outSum += outBuf[i] ?? 0
337
- inSum += inBuf[i] ?? 0
338
- }
339
- const outAvg = outSum / (half * 255)
340
- const inAvg = inSum / (half * 255)
341
- // Punch curve so quiet ambient noise doesn't dominate, peaks pop.
342
- const raw = Math.max(outAvg, inAvg * 0.7)
343
- const shaped = Math.min(1, Math.pow(raw, 0.7) * 1.4)
344
- // Smooth toward target so visuals don't jitter at 60fps.
345
- levelRef.current = levelRef.current + (shaped - levelRef.current) * 0.35
346
- rafRef.current = requestAnimationFrame(tick)
347
- }
348
- rafRef.current = requestAnimationFrame(tick)
349
-
350
- // 4. Drain the AsyncIterable. We don't await — it runs until the
351
- // session closes. React keeps re-rendering as state updates fire.
352
- void (async () => {
353
- for await (const event of session.events) {
354
- options.onEvent?.(event)
355
- resetIdleTimer()
356
- switch (event.type) {
357
- case "user-transcript-delta":
358
- setUserTranscript((t) => t + event.text)
359
- break
360
- case "user-transcript-final":
361
- // The final text is already committed downstream via
362
- // onRealtimeEvent → fireUserTurn / chat.applyEvent. Clear the
363
- // live ribbon IMMEDIATELY so the next turn's deltas don't
364
- // paint on top of the previous turn's final text (which would
365
- // appear as "message mới ghi đè lên block trước rồi mới
366
- // reveal block mới").
367
- setUserTranscript("")
368
- break
369
- case "agent-transcript-delta":
370
- setAgentTranscript((t) => t + event.text)
371
- break
372
- case "agent-transcript-final":
373
- // Same rationale as user-transcript-final: the assistant text
374
- // is already committed via chat.applyEvent text-delta stream.
375
- // Drop the live ribbon now so the RealtimeRecents live row
376
- // doesn't keep showing Turn-N's text while Turn-(N+1) starts
377
- // streaming (Gemini may emit Turn-(N+1) deltas BEFORE
378
- // turn-complete arrives for Turn-N).
379
- setAgentTranscript("")
380
- break
381
- case "tool-call":
382
- setLastToolCall({ name: event.name, args: event.args })
383
- setToolRunning(true)
384
- break
385
- case "tool-result":
386
- case "tool-error":
387
- // Tool finished (success or failure). Drop back out of the
388
- // `thinking` orb state so the orb returns to listening /
389
- // speaking based on subsequent audio activity.
390
- setToolRunning(false)
391
- break
392
- case "barge-in":
393
- // The session itself stops audio; we just refresh the
394
- // user-transcript ribbon so old text doesn't linger.
395
- setAgentTranscript("")
396
- break
397
- case "turn-complete":
398
- // Once Gemini signals end of turn the assistant text is already
399
- // committed into chat.nodes via agent-transcript-final. Clear
400
- // BOTH live ribbons so the next turn starts fresh and the
401
- // RealtimeRecents live row doesn't duplicate the just-committed
402
- // assistant bubble.
403
- setUserTranscript("")
404
- setAgentTranscript("")
405
- break
406
- case "error":
407
- setError(event.message)
408
- break
409
- case "closed":
410
- setStatus("idle")
411
- break
412
- }
413
- }
414
- })()
415
- }, [cleanup, options, resetIdleTimer, status])
416
-
417
- const hangup = useCallback(async () => {
418
- if (status === "idle") return
419
- setStatus("ending")
420
- await cleanup()
421
- setStatus("idle")
422
- }, [cleanup, status])
423
-
424
- const setMuted = useCallback((next: boolean) => {
425
- setMutedState(next)
426
- sessionRef.current?.mute(next)
427
- }, [])
428
-
429
- // Cleanup on unmount — important when the overlay is mounted/unmounted.
430
- useEffect(
431
- () => () => {
432
- void cleanup()
433
- },
434
- [cleanup],
435
- )
436
-
437
- return {
438
- status,
439
- error,
440
- userTranscript,
441
- agentTranscript,
442
- lastToolCall,
443
- toolRunning,
444
- muted,
445
- start,
446
- hangup,
447
- setMuted,
448
- levelRef,
449
- outputAnalyser,
450
- inputAnalyser,
451
- }
452
- }
package/src/index.ts DELETED
@@ -1,45 +0,0 @@
1
- // @tinyweb-agent-framework/chat-ui — public entrypoint.
2
- //
3
- // Stays intentionally small. The default export is `<TinywebChat />`; the
4
- // rest are advanced building blocks for consumers that want to ship a
5
- // bespoke shell on top of the same NDJSON + state machine.
6
-
7
- export { TinywebChat } from "./components/TinywebChat"
8
- export { useAgentChat } from "./hooks/useAgentChat"
9
- export type { ChatStatus, SendOptions, UseAgentChatOptions, UseAgentChatReturn } from "./hooks/useAgentChat"
10
- export { useRealtimeCall } from "./hooks/useRealtimeCall"
11
- export type {
12
- CallStatus,
13
- ToolHandlerMap,
14
- UseRealtimeCallOptions,
15
- UseRealtimeCallReturn,
16
- } from "./hooks/useRealtimeCall"
17
- export { RealtimeCallOverlay } from "./components/RealtimeCallOverlay"
18
- export type { RealtimeCallOverlayProps } from "./components/RealtimeCallOverlay"
19
- export { RealtimeOrb } from "./components/RealtimeOrb"
20
- export type {
21
- RealtimeOrbProps,
22
- RealtimeOrbSpeaker,
23
- RealtimeOrbState,
24
- } from "./components/RealtimeOrb"
25
- export { WireOrbEffect } from "./components/WireOrbEffect"
26
- export type { WireOrbEffectProps, WireOrbState } from "./components/WireOrbEffect"
27
- export { renderMarkdown } from "./markdown/render"
28
- export { extractExec, extractToolImage, truncateBase64InJson } from "./util/tool-detect"
29
- export type { ExecPayload, ImagePayload } from "./util/tool-detect"
30
- export { friendlyToolLabel } from "./util/tool-labels"
31
- export { defaultToolRenderers } from "./components/tool/builtinRenderers"
32
- export { ToolCard } from "./components/tool/ToolCard"
33
- export type { ToolCardProps } from "./components/tool/ToolCard"
34
- export type {
35
- AttachmentLimits,
36
- ChatMessage,
37
- ChatTheme,
38
- CondenseState,
39
- ImageAttachment,
40
- RealtimeProp,
41
- TinywebChatProps,
42
- ToolRenderer,
43
- ToolRendererContext,
44
- TranscriptNode,
45
- } from "./types"
@@ -1,121 +0,0 @@
1
- // Dependency-free markdown renderer for assistant bubbles.
2
- //
3
- // Ported verbatim (with TypeScript types only) from
4
- // [`examples/device-pilot/public/app.js`](../../../../examples/device-pilot/public/app.js:176)
5
- // `renderMarkdown`. The implementation is intentionally minimal — it covers
6
- // what the model emits in chat (fenced code, inline code, bold/italic,
7
- // links, lists, headings, paragraphs) and nothing else.
8
- //
9
- // XSS-safety: the source is fully `escapeHtml`-ed BEFORE any markup is
10
- // reintroduced, so callers can inject the result via `dangerouslySetInnerHTML`
11
- // without risk of script injection. Don't reorder the passes — the placeholder
12
- // trick for code blocks is what keeps `*`/`_` inside code from being treated
13
- // as emphasis markers.
14
-
15
- import { escapeHtml } from "../util/escape"
16
-
17
- export const renderMarkdown = (src: string | null | undefined): string => {
18
- if (!src) return ""
19
-
20
- // 1. Extract fenced code blocks first so their contents bypass the
21
- // rest of the pipeline (otherwise `*` / `_` inside code would be
22
- // mis-parsed as emphasis).
23
- const codeBlocks: Array<{ lang: string; body: string }> = []
24
- let work = String(src).replace(/```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/g, (_m, lang: string, body: string) => {
25
- const i = codeBlocks.push({ lang, body }) - 1
26
- return "\u0000CODEBLOCK" + i + "\u0000"
27
- })
28
-
29
- // 2. Escape EVERYTHING. From here on all transforms emit safe HTML.
30
- work = escapeHtml(work)
31
-
32
- // 3. Inline code — same placeholder trick so emphasis can't touch it.
33
- const inlineCodes: string[] = []
34
- work = work.replace(/`([^`\n]+)`/g, (_m, body: string) => {
35
- const i = inlineCodes.push(body) - 1
36
- return "\u0000INLINECODE" + i + "\u0000"
37
- })
38
-
39
- // 4. Explicit links: [label](url). URL is already escaped by step 2.
40
- work = work.replace(
41
- /\[([^\]]+)\]\(([^)\s]+)\)/g,
42
- (_m, label: string, url: string) =>
43
- '<a href="' + url + '" target="_blank" rel="noopener noreferrer">' + label + "</a>",
44
- )
45
-
46
- // 5. Bare URLs — but only when not already inside an href attribute.
47
- work = work.replace(
48
- /(?<!["=>])\b(https?:\/\/[^\s<]+[^\s<.,;:!?)\]'"])/g,
49
- (m) => '<a href="' + m + '" target="_blank" rel="noopener noreferrer">' + m + "</a>",
50
- )
51
-
52
- // 6. Emphasis — bold before italic so **x** isn't grabbed by the italic pass.
53
- work = work.replace(/\*\*([^*\n]+)\*\*/g, "<strong>$1</strong>")
54
- work = work.replace(/__([^_\n]+)__/g, "<strong>$1</strong>")
55
- work = work.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, "$1<em>$2</em>")
56
- work = work.replace(/(^|[^_])_([^_\n]+)_(?!_)/g, "$1<em>$2</em>")
57
-
58
- // 7. Block-level passes. Walk line-by-line so headings, lists and
59
- // paragraphs can coexist. ATX headings must be detected BEFORE the
60
- // paragraph pass folds them into <p> blocks.
61
- const lines = work.split("\n")
62
- const out: string[] = []
63
- let i = 0
64
- while (i < lines.length) {
65
- const line = lines[i] ?? ""
66
-
67
- // 7a. ATX heading: 1-6 leading #'s + space + content.
68
- const h = line.match(/^\s*(#{1,6})\s+(.*?)\s*#*\s*$/)
69
- if (h) {
70
- const level = (h[1] ?? "").length
71
- out.push("<h" + level + ">" + h[2] + "</h" + level + ">")
72
- i++
73
- continue
74
- }
75
-
76
- const ol = line.match(/^\s*\d+\.\s+(.*)$/)
77
- const ul = line.match(/^\s*[-*]\s+(.*)$/)
78
- if (ol || ul) {
79
- const tag = ol ? "ol" : "ul"
80
- const re = ol ? /^\s*\d+\.\s+(.*)$/ : /^\s*[-*]\s+(.*)$/
81
- const items: string[] = []
82
- while (i < lines.length) {
83
- const m = (lines[i] ?? "").match(re)
84
- if (!m) break
85
- items.push("<li>" + m[1] + "</li>")
86
- i++
87
- }
88
- out.push("<" + tag + ">" + items.join("") + "</" + tag + ">")
89
- continue
90
- }
91
- out.push(line)
92
- i++
93
- }
94
- work = out.join("\n")
95
-
96
- // 8. Paragraphs: split on blank lines, intra-paragraph newlines → <br>.
97
- work = work
98
- .split(/\n{2,}/)
99
- .map((chunk) => {
100
- const trimmed = chunk.trim()
101
- if (!trimmed) return ""
102
- if (/^<(ul|ol|pre|h\d|blockquote)\b/i.test(trimmed)) return trimmed
103
- return "<p>" + trimmed.replace(/\n/g, "<br>") + "</p>"
104
- })
105
- .filter(Boolean)
106
- .join("")
107
-
108
- // 9. Restore inline code and fenced code blocks.
109
- work = work.replace(/\u0000INLINECODE(\d+)\u0000/g, (_m, idx: string) => {
110
- const body = inlineCodes[Number(idx)] ?? ""
111
- return "<code>" + escapeHtml(body) + "</code>"
112
- })
113
- work = work.replace(/\u0000CODEBLOCK(\d+)\u0000/g, (_m, idx: string) => {
114
- const block = codeBlocks[Number(idx)]
115
- if (!block) return ""
116
- const cls = block.lang ? ' class="lang-' + escapeHtml(block.lang) + '"' : ""
117
- return "<pre><code" + cls + ">" + escapeHtml(block.body) + "</code></pre>"
118
- })
119
-
120
- return work
121
- }