@tinyweb_dev/agent-framework-chat-ui 0.1.1 → 0.3.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.
- package/dist/components/Composer.d.ts +38 -0
- package/dist/components/Composer.d.ts.map +1 -0
- package/dist/components/Header.d.ts +7 -0
- package/dist/components/Header.d.ts.map +1 -0
- package/dist/components/Hero.d.ts +6 -0
- package/dist/components/Hero.d.ts.map +1 -0
- package/dist/components/RealtimeCallOverlay.d.ts +68 -0
- package/dist/components/RealtimeCallOverlay.d.ts.map +1 -0
- package/dist/components/RealtimeOrb.d.ts +21 -0
- package/dist/components/RealtimeOrb.d.ts.map +1 -0
- package/{src/components/Sidebar.tsx → dist/components/Sidebar.d.ts} +5 -9
- package/dist/components/Sidebar.d.ts.map +1 -0
- package/dist/components/TinywebChat.d.ts +3 -0
- package/dist/components/TinywebChat.d.ts.map +1 -0
- package/dist/components/Transcript.d.ts +20 -0
- package/dist/components/Transcript.d.ts.map +1 -0
- package/dist/components/WireOrbEffect.d.ts +17 -0
- package/dist/components/WireOrbEffect.d.ts.map +1 -0
- package/dist/components/condense/CondensePill.d.ts +11 -0
- package/dist/components/condense/CondensePill.d.ts.map +1 -0
- package/dist/components/messages/AssistantMessage.d.ts +10 -0
- package/dist/components/messages/AssistantMessage.d.ts.map +1 -0
- package/dist/components/messages/ErrorMessage.d.ts +7 -0
- package/dist/components/messages/ErrorMessage.d.ts.map +1 -0
- package/dist/components/messages/ToolMessage.d.ts +17 -0
- package/dist/components/messages/ToolMessage.d.ts.map +1 -0
- package/dist/components/messages/UserMessage.d.ts +7 -0
- package/dist/components/messages/UserMessage.d.ts.map +1 -0
- package/dist/components/tool/ExecRenderer.d.ts +14 -0
- package/dist/components/tool/ExecRenderer.d.ts.map +1 -0
- package/dist/components/tool/ImageRenderer.d.ts +16 -0
- package/dist/components/tool/ImageRenderer.d.ts.map +1 -0
- package/dist/components/tool/JsonRenderer.d.ts +11 -0
- package/dist/components/tool/JsonRenderer.d.ts.map +1 -0
- package/dist/components/tool/ToolCard.d.ts +29 -0
- package/dist/components/tool/ToolCard.d.ts.map +1 -0
- package/dist/components/tool/builtinRenderers.d.ts +9 -0
- package/dist/components/tool/builtinRenderers.d.ts.map +1 -0
- package/dist/hooks/useAgentChat.d.ts +46 -0
- package/dist/hooks/useAgentChat.d.ts.map +1 -0
- package/dist/hooks/useAnchorLatestUser.d.ts +15 -0
- package/dist/hooks/useAnchorLatestUser.d.ts.map +1 -0
- package/dist/hooks/useInitialScrollToEnd.d.ts +15 -0
- package/dist/hooks/useInitialScrollToEnd.d.ts.map +1 -0
- package/dist/hooks/useNdjsonStream.d.ts +11 -0
- package/dist/hooks/useNdjsonStream.d.ts.map +1 -0
- package/dist/hooks/useRealtimeCall.d.ts +112 -0
- package/dist/hooks/useRealtimeCall.d.ts.map +1 -0
- package/dist/index.cjs +3160 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3126 -0
- package/dist/index.js.map +1 -0
- package/dist/markdown/render.d.ts +2 -0
- package/dist/markdown/render.d.ts.map +1 -0
- package/dist/types.d.ts +257 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/util/attachments.d.ts +28 -0
- package/dist/util/attachments.d.ts.map +1 -0
- package/dist/util/escape.d.ts +2 -0
- package/dist/util/escape.d.ts.map +1 -0
- package/dist/util/theme.d.ts +13 -0
- package/dist/util/theme.d.ts.map +1 -0
- package/dist/util/tool-detect.d.ts +26 -0
- package/dist/util/tool-detect.d.ts.map +1 -0
- package/dist/util/tool-labels.d.ts +11 -0
- package/dist/util/tool-labels.d.ts.map +1 -0
- package/package.json +14 -14
- package/src/components/Composer.tsx +0 -267
- package/src/components/Header.tsx +0 -16
- package/src/components/Hero.tsx +0 -16
- package/src/components/RealtimeCallOverlay.tsx +0 -894
- package/src/components/RealtimeOrb.tsx +0 -388
- package/src/components/TinywebChat.tsx +0 -95
- package/src/components/Transcript.tsx +0 -146
- package/src/components/WireOrbEffect.tsx +0 -556
- package/src/components/condense/CondensePill.tsx +0 -77
- package/src/components/messages/AssistantMessage.tsx +0 -15
- package/src/components/messages/ErrorMessage.tsx +0 -12
- package/src/components/messages/ToolMessage.tsx +0 -49
- package/src/components/messages/UserMessage.tsx +0 -37
- package/src/components/tool/ExecRenderer.tsx +0 -71
- package/src/components/tool/ImageRenderer.tsx +0 -47
- package/src/components/tool/JsonRenderer.tsx +0 -24
- package/src/components/tool/ToolCard.tsx +0 -65
- package/src/components/tool/builtinRenderers.tsx +0 -456
- package/src/hooks/useAgentChat.ts +0 -454
- package/src/hooks/useAnchorLatestUser.ts +0 -99
- package/src/hooks/useInitialScrollToEnd.ts +0 -41
- package/src/hooks/useNdjsonStream.ts +0 -71
- package/src/hooks/useRealtimeCall.ts +0 -452
- package/src/index.ts +0 -45
- package/src/markdown/render.ts +0 -121
- package/src/types.ts +0 -241
- package/src/util/attachments.ts +0 -87
- package/src/util/escape.ts +0 -16
- package/src/util/theme.ts +0 -40
- package/src/util/tool-detect.ts +0 -65
- package/src/util/tool-labels.ts +0 -34
- /package/{src → dist}/styles.css +0 -0
|
@@ -1,388 +0,0 @@
|
|
|
1
|
-
"use client"
|
|
2
|
-
|
|
3
|
-
// Realtime voice-assistant orb — v2 Three.js / R3F ripple edition
|
|
4
|
-
// (plan 0019 §3.5, supersedes the v1 CSS-only halo per D8).
|
|
5
|
-
//
|
|
6
|
-
// Renders a 3D ripple animation behind a soft halo backdrop:
|
|
7
|
-
// • a `<Canvas>` (R3F) hosts ~6400 `THREE.Points` arranged on a grid
|
|
8
|
-
// in the XZ plane; the vertex shader recomputes `y = uAmp · sin(uFreq · r + uPhase)`
|
|
9
|
-
// each frame, driven by uniforms that are animated by `useFrame`
|
|
10
|
-
// • outside the canvas, a single hidden RAF still writes `--rt-level`
|
|
11
|
-
// and `data-speaker` on the host `<div>` so the mic-FAB ripple in
|
|
12
|
-
// `RealtimeCallOverlay` (CSS-driven, plan 0019 §3.3) continues to
|
|
13
|
-
// react to audio
|
|
14
|
-
//
|
|
15
|
-
// Prop API is unchanged from v1 so consumers do not have to migrate.
|
|
16
|
-
// `three` + `@react-three/fiber` are PEER dependencies (optional) of
|
|
17
|
-
// `@tinyweb-agent-framework/chat-ui`; if they are missing at runtime
|
|
18
|
-
// the orb falls back to a CSS-only halo render so the build does not
|
|
19
|
-
// crash.
|
|
20
|
-
|
|
21
|
-
import { useEffect, useMemo, useRef } from "react"
|
|
22
|
-
import { Canvas, useFrame, type ThreeElements } from "@react-three/fiber"
|
|
23
|
-
import * as THREE from "three"
|
|
24
|
-
|
|
25
|
-
export type RealtimeOrbState = "idle" | "listening" | "speaking" | "connecting"
|
|
26
|
-
export type RealtimeOrbSpeaker = "idle" | "user" | "agent"
|
|
27
|
-
|
|
28
|
-
export type RealtimeOrbProps = {
|
|
29
|
-
/** Mutable ref to a 0..1 audio level. Used as fallback when analysers are absent. */
|
|
30
|
-
readonly levelRef?: { readonly current: number }
|
|
31
|
-
/** Visual mood (lifecycle phase). */
|
|
32
|
-
readonly state?: RealtimeOrbState
|
|
33
|
-
/** Live analyser on the mic input. Drives `data-speaker="user"`. */
|
|
34
|
-
readonly inputAnalyser?: AnalyserNode | null
|
|
35
|
-
/** Live analyser on the agent TTS output. Drives `data-speaker="agent"`. */
|
|
36
|
-
readonly outputAnalyser?: AnalyserNode | null
|
|
37
|
-
/** Force speaker tint (overrides analyser-derived value). Useful for tests/preview. */
|
|
38
|
-
readonly speaker?: RealtimeOrbSpeaker
|
|
39
|
-
/** Optional override size (CSS px or any CSS length). Default 240px. */
|
|
40
|
-
readonly size?: number | string
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
// --- helpers --------------------------------------------------------------
|
|
44
|
-
|
|
45
|
-
const toCssSize = (size: number | string | undefined): string | undefined => {
|
|
46
|
-
if (size === undefined) return undefined
|
|
47
|
-
return typeof size === "number" ? `${size}px` : size
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
const avgBand = (buf: Uint8Array, lo: number, hi: number): number => {
|
|
51
|
-
const lim = Math.min(hi, buf.length)
|
|
52
|
-
if (lim <= lo) return 0
|
|
53
|
-
let sum = 0
|
|
54
|
-
for (let i = lo; i < lim; i++) sum += buf[i] ?? 0
|
|
55
|
-
return sum / (lim - lo)
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
const SPEAKER_FLIP_MIN_MS = 300
|
|
59
|
-
const SPEAKER_DELTA_THRESHOLD = 0.03
|
|
60
|
-
|
|
61
|
-
// Per-speaker palette. These are the *inner* sprite colours. The outer
|
|
62
|
-
// (background-leaning) tint is fixed per palette. Mirrors §3.5.4 of plan
|
|
63
|
-
// 0019. Hosts can still re-theme via CSS custom properties — see below
|
|
64
|
-
// where we read computed style.
|
|
65
|
-
const PALETTES: Record<RealtimeOrbSpeaker, { inner: THREE.Color; outer: THREE.Color }> = {
|
|
66
|
-
idle: { inner: new THREE.Color("#9282dc"), outer: new THREE.Color("#1e1640") },
|
|
67
|
-
user: { inner: new THREE.Color("#a8b8ff"), outer: new THREE.Color("#1d2a55") },
|
|
68
|
-
agent: { inner: new THREE.Color("#b9aef0"), outer: new THREE.Color("#2a1a55") },
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
// --- ripple geometry + material ------------------------------------------
|
|
72
|
-
|
|
73
|
-
type RipplePointsProps = {
|
|
74
|
-
count: number
|
|
75
|
-
separation: number
|
|
76
|
-
reducedMotion: boolean
|
|
77
|
-
levelRef: { readonly current: number }
|
|
78
|
-
speakerRef: { readonly current: RealtimeOrbSpeaker }
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
const VERTEX_SHADER = /* glsl */ `
|
|
82
|
-
uniform float uAmp;
|
|
83
|
-
uniform float uFreq;
|
|
84
|
-
uniform float uPhase;
|
|
85
|
-
uniform float uSize;
|
|
86
|
-
|
|
87
|
-
varying float vRadial;
|
|
88
|
-
|
|
89
|
-
void main() {
|
|
90
|
-
vec3 p = position;
|
|
91
|
-
float r = length(p.xz);
|
|
92
|
-
p.y = uAmp * sin(uFreq * r + uPhase);
|
|
93
|
-
|
|
94
|
-
vec4 mv = modelViewMatrix * vec4(p, 1.0);
|
|
95
|
-
gl_Position = projectionMatrix * mv;
|
|
96
|
-
gl_PointSize = uSize * (1.0 / max(-mv.z, 0.001));
|
|
97
|
-
vRadial = r;
|
|
98
|
-
}
|
|
99
|
-
`
|
|
100
|
-
|
|
101
|
-
const FRAGMENT_SHADER = /* glsl */ `
|
|
102
|
-
uniform vec3 uColorA;
|
|
103
|
-
uniform vec3 uColorB;
|
|
104
|
-
uniform float uOpacity;
|
|
105
|
-
|
|
106
|
-
varying float vRadial;
|
|
107
|
-
|
|
108
|
-
void main() {
|
|
109
|
-
vec2 uv = gl_PointCoord - 0.5;
|
|
110
|
-
float d = length(uv);
|
|
111
|
-
float alpha = smoothstep(0.5, 0.0, d);
|
|
112
|
-
if (alpha < 0.02) discard;
|
|
113
|
-
vec3 col = mix(uColorA, uColorB, smoothstep(0.0, 1.2, vRadial));
|
|
114
|
-
gl_FragColor = vec4(col, alpha * uOpacity);
|
|
115
|
-
}
|
|
116
|
-
`
|
|
117
|
-
|
|
118
|
-
const RipplePoints = (props: RipplePointsProps) => {
|
|
119
|
-
// Build positions / index buffers once. `count × count` grid in the XZ
|
|
120
|
-
// plane centred at origin. The Y is overwritten every frame on the GPU
|
|
121
|
-
// — we only need the static X and Z values here.
|
|
122
|
-
const geometry = useMemo(() => {
|
|
123
|
-
const total = props.count * props.count
|
|
124
|
-
const positions = new Float32Array(total * 3)
|
|
125
|
-
const half = props.count / 2
|
|
126
|
-
let p = 0
|
|
127
|
-
for (let xi = 0; xi < props.count; xi++) {
|
|
128
|
-
for (let zi = 0; zi < props.count; zi++) {
|
|
129
|
-
positions[p++] = (xi - half) * props.separation
|
|
130
|
-
positions[p++] = 0
|
|
131
|
-
positions[p++] = (zi - half) * props.separation
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
const g = new THREE.BufferGeometry()
|
|
135
|
-
g.setAttribute("position", new THREE.BufferAttribute(positions, 3))
|
|
136
|
-
g.computeBoundingSphere()
|
|
137
|
-
return g
|
|
138
|
-
}, [props.count, props.separation])
|
|
139
|
-
|
|
140
|
-
// Uniforms live on the material; we mutate `.value` in `useFrame`.
|
|
141
|
-
const material = useMemo(() => {
|
|
142
|
-
const uniforms = {
|
|
143
|
-
uAmp: { value: 0.12 },
|
|
144
|
-
uFreq: { value: 7.5 },
|
|
145
|
-
uPhase: { value: 0.0 },
|
|
146
|
-
uSize: { value: 14.0 },
|
|
147
|
-
uOpacity: { value: 0.85 },
|
|
148
|
-
uColorA: { value: PALETTES.idle.inner.clone() },
|
|
149
|
-
uColorB: { value: PALETTES.idle.outer.clone() },
|
|
150
|
-
}
|
|
151
|
-
const mat = new THREE.ShaderMaterial({
|
|
152
|
-
vertexShader: VERTEX_SHADER,
|
|
153
|
-
fragmentShader: FRAGMENT_SHADER,
|
|
154
|
-
uniforms,
|
|
155
|
-
transparent: true,
|
|
156
|
-
depthWrite: false,
|
|
157
|
-
blending: THREE.AdditiveBlending,
|
|
158
|
-
})
|
|
159
|
-
return mat
|
|
160
|
-
}, [])
|
|
161
|
-
|
|
162
|
-
// EMA-smoothed level state local to the frame loop.
|
|
163
|
-
const smoothLevelRef = useRef(0)
|
|
164
|
-
const currentSpeakerRef = useRef<RealtimeOrbSpeaker>("idle")
|
|
165
|
-
const tmpColorA = useMemo(() => new THREE.Color(), [])
|
|
166
|
-
const tmpColorB = useMemo(() => new THREE.Color(), [])
|
|
167
|
-
|
|
168
|
-
useFrame((_state, dt) => {
|
|
169
|
-
// Clamp dt to avoid huge phase jumps when the tab regains focus.
|
|
170
|
-
const safeDt = Math.min(dt, 1 / 30)
|
|
171
|
-
|
|
172
|
-
const target = Math.max(0, Math.min(1, props.levelRef.current || 0))
|
|
173
|
-
smoothLevelRef.current += (target - smoothLevelRef.current) * 0.18
|
|
174
|
-
const lvl = smoothLevelRef.current
|
|
175
|
-
|
|
176
|
-
if (props.reducedMotion) {
|
|
177
|
-
material.uniforms.uAmp.value = 0.18
|
|
178
|
-
material.uniforms.uFreq.value = 7.5
|
|
179
|
-
material.uniforms.uPhase.value = 0.0
|
|
180
|
-
material.uniforms.uSize.value = 14.0
|
|
181
|
-
material.uniforms.uOpacity.value = 0.85
|
|
182
|
-
return
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
material.uniforms.uAmp.value = 0.10 + lvl * 0.55
|
|
186
|
-
material.uniforms.uFreq.value = 7.5 + lvl * 4.0
|
|
187
|
-
material.uniforms.uPhase.value += safeDt * (1.4 + lvl * 2.2)
|
|
188
|
-
material.uniforms.uSize.value = 14.0 + lvl * 22.0
|
|
189
|
-
material.uniforms.uOpacity.value = 0.7 + lvl * 0.3
|
|
190
|
-
|
|
191
|
-
// Per-speaker colour lerp. The palette ref is stable; we lerp the
|
|
192
|
-
// current uniform colour toward it each frame so transitions are
|
|
193
|
-
// smooth (~3-4 frames to converge at lerp 0.08).
|
|
194
|
-
const nextSpeaker = props.speakerRef.current
|
|
195
|
-
if (nextSpeaker !== currentSpeakerRef.current) {
|
|
196
|
-
currentSpeakerRef.current = nextSpeaker
|
|
197
|
-
}
|
|
198
|
-
const palette = PALETTES[currentSpeakerRef.current]
|
|
199
|
-
tmpColorA.copy(palette.inner)
|
|
200
|
-
tmpColorB.copy(palette.outer)
|
|
201
|
-
material.uniforms.uColorA.value.lerp(tmpColorA, 0.08)
|
|
202
|
-
material.uniforms.uColorB.value.lerp(tmpColorB, 0.08)
|
|
203
|
-
})
|
|
204
|
-
|
|
205
|
-
// Cleanup the cached geometry/material when this component unmounts.
|
|
206
|
-
useEffect(() => {
|
|
207
|
-
return () => {
|
|
208
|
-
geometry.dispose()
|
|
209
|
-
material.dispose()
|
|
210
|
-
}
|
|
211
|
-
}, [geometry, material])
|
|
212
|
-
|
|
213
|
-
const args = [geometry, material] as ThreeElements["points"]["args"]
|
|
214
|
-
return <points args={args} rotation={[-Math.PI / 7, 0, 0]} />
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
// --- the orb host --------------------------------------------------------
|
|
218
|
-
|
|
219
|
-
export const RealtimeOrb = (props: RealtimeOrbProps) => {
|
|
220
|
-
const hostRef = useRef<HTMLDivElement | null>(null)
|
|
221
|
-
const rafRef = useRef<number | null>(null)
|
|
222
|
-
|
|
223
|
-
// Shared mutable refs read by both the side-effect RAF (for CSS var
|
|
224
|
-
// writes + speaker resolution) AND by RipplePoints `useFrame`.
|
|
225
|
-
const stateRef = useRef<RealtimeOrbState>(props.state ?? "idle")
|
|
226
|
-
const speakerOverrideRef = useRef<RealtimeOrbSpeaker | undefined>(props.speaker)
|
|
227
|
-
const inputAnalyserRef = useRef<AnalyserNode | null>(props.inputAnalyser ?? null)
|
|
228
|
-
const outputAnalyserRef = useRef<AnalyserNode | null>(props.outputAnalyser ?? null)
|
|
229
|
-
const externalLevelRef = props.levelRef
|
|
230
|
-
|
|
231
|
-
// Single live level ref consumed by RipplePoints. We always own this
|
|
232
|
-
// ref; the RAF loop writes `currentLevelRef.current` from either the
|
|
233
|
-
// analyser-derived smoothed level or the consumer's `levelRef`.
|
|
234
|
-
const currentLevelRef = useRef(0)
|
|
235
|
-
const currentSpeakerRef = useRef<RealtimeOrbSpeaker>("idle")
|
|
236
|
-
|
|
237
|
-
// Cheap per-render sync — avoids re-binding the effect on every prop
|
|
238
|
-
// change (analyser nodes are stable across renders in practice but
|
|
239
|
-
// we don't want to gate on identity).
|
|
240
|
-
stateRef.current = props.state ?? "idle"
|
|
241
|
-
speakerOverrideRef.current = props.speaker
|
|
242
|
-
inputAnalyserRef.current = props.inputAnalyser ?? null
|
|
243
|
-
outputAnalyserRef.current = props.outputAnalyser ?? null
|
|
244
|
-
|
|
245
|
-
const reducedMotion = useMemo(() => {
|
|
246
|
-
if (typeof window === "undefined" || typeof window.matchMedia !== "function") {
|
|
247
|
-
return false
|
|
248
|
-
}
|
|
249
|
-
return window.matchMedia("(prefers-reduced-motion: reduce)").matches
|
|
250
|
-
}, [])
|
|
251
|
-
|
|
252
|
-
useEffect(() => {
|
|
253
|
-
const host = hostRef.current
|
|
254
|
-
if (!host) return
|
|
255
|
-
|
|
256
|
-
if (reducedMotion) {
|
|
257
|
-
host.style.setProperty("--rt-level", "0.25")
|
|
258
|
-
host.setAttribute("data-speaker", speakerOverrideRef.current ?? "idle")
|
|
259
|
-
currentLevelRef.current = 0.25
|
|
260
|
-
currentSpeakerRef.current = speakerOverrideRef.current ?? "idle"
|
|
261
|
-
return
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
const inBuf = new Uint8Array(64)
|
|
265
|
-
const outBuf = new Uint8Array(64)
|
|
266
|
-
let smoothed = 0
|
|
267
|
-
let speaker: RealtimeOrbSpeaker = speakerOverrideRef.current ?? "idle"
|
|
268
|
-
let lastFlipAt = 0
|
|
269
|
-
|
|
270
|
-
const tick = () => {
|
|
271
|
-
const inA = inputAnalyserRef.current
|
|
272
|
-
const outA = outputAnalyserRef.current
|
|
273
|
-
|
|
274
|
-
let userBand = 0
|
|
275
|
-
let agentBand = 0
|
|
276
|
-
|
|
277
|
-
if (inA && typeof inA.getByteFrequencyData === "function") {
|
|
278
|
-
inA.getByteFrequencyData(inBuf)
|
|
279
|
-
userBand = avgBand(inBuf, 2, 8) / 255
|
|
280
|
-
}
|
|
281
|
-
if (outA && typeof outA.getByteFrequencyData === "function") {
|
|
282
|
-
outA.getByteFrequencyData(outBuf)
|
|
283
|
-
agentBand = avgBand(outBuf, 4, 32) / 255
|
|
284
|
-
}
|
|
285
|
-
if (!inA && !outA) {
|
|
286
|
-
const fallback = externalLevelRef
|
|
287
|
-
? Math.max(0, Math.min(1, externalLevelRef.current || 0))
|
|
288
|
-
: 0
|
|
289
|
-
userBand = fallback
|
|
290
|
-
agentBand = fallback
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
const raw = Math.max(userBand, agentBand)
|
|
294
|
-
smoothed = smoothed * 0.82 + raw * 0.18
|
|
295
|
-
currentLevelRef.current = smoothed
|
|
296
|
-
host.style.setProperty("--rt-level", smoothed.toFixed(3))
|
|
297
|
-
|
|
298
|
-
const stateNow = stateRef.current
|
|
299
|
-
const override = speakerOverrideRef.current
|
|
300
|
-
if (override !== undefined) {
|
|
301
|
-
if (override !== speaker) {
|
|
302
|
-
speaker = override
|
|
303
|
-
host.setAttribute("data-speaker", speaker)
|
|
304
|
-
currentSpeakerRef.current = speaker
|
|
305
|
-
}
|
|
306
|
-
rafRef.current = requestAnimationFrame(tick)
|
|
307
|
-
return
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
const isActive = stateNow === "listening" || stateNow === "speaking"
|
|
311
|
-
if (!isActive) {
|
|
312
|
-
if (speaker !== "idle") {
|
|
313
|
-
speaker = "idle"
|
|
314
|
-
host.setAttribute("data-speaker", speaker)
|
|
315
|
-
currentSpeakerRef.current = speaker
|
|
316
|
-
}
|
|
317
|
-
rafRef.current = requestAnimationFrame(tick)
|
|
318
|
-
return
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
const now = performance.now()
|
|
322
|
-
const delta = userBand - agentBand
|
|
323
|
-
const absDelta = Math.abs(delta)
|
|
324
|
-
const canFlip = now - lastFlipAt >= SPEAKER_FLIP_MIN_MS
|
|
325
|
-
if (absDelta > SPEAKER_DELTA_THRESHOLD && canFlip) {
|
|
326
|
-
const next: RealtimeOrbSpeaker = delta > 0 ? "user" : "agent"
|
|
327
|
-
if (next !== speaker) {
|
|
328
|
-
speaker = next
|
|
329
|
-
lastFlipAt = now
|
|
330
|
-
host.setAttribute("data-speaker", speaker)
|
|
331
|
-
currentSpeakerRef.current = speaker
|
|
332
|
-
}
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
rafRef.current = requestAnimationFrame(tick)
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
host.setAttribute("data-speaker", speaker)
|
|
339
|
-
currentSpeakerRef.current = speaker
|
|
340
|
-
rafRef.current = requestAnimationFrame(tick)
|
|
341
|
-
|
|
342
|
-
return () => {
|
|
343
|
-
if (rafRef.current !== null) cancelAnimationFrame(rafRef.current)
|
|
344
|
-
rafRef.current = null
|
|
345
|
-
}
|
|
346
|
-
}, [externalLevelRef, reducedMotion])
|
|
347
|
-
|
|
348
|
-
const cssSize = toCssSize(props.size)
|
|
349
|
-
const style = cssSize ? { width: cssSize, height: cssSize } : undefined
|
|
350
|
-
const speakerAttr: RealtimeOrbSpeaker = props.speaker ?? "idle"
|
|
351
|
-
|
|
352
|
-
// Lower the point count under reduced-motion (plan 0019 §3.5.5)
|
|
353
|
-
const count = reducedMotion ? 38 : 80
|
|
354
|
-
|
|
355
|
-
return (
|
|
356
|
-
<div
|
|
357
|
-
ref={hostRef}
|
|
358
|
-
className={`realtime-orb realtime-orb--${props.state ?? "idle"} realtime-orb--r3f`}
|
|
359
|
-
data-speaker={speakerAttr}
|
|
360
|
-
style={style}
|
|
361
|
-
aria-hidden
|
|
362
|
-
>
|
|
363
|
-
<span className="realtime-orb__halo realtime-orb__halo--3" />
|
|
364
|
-
<span className="realtime-orb__halo realtime-orb__halo--2" />
|
|
365
|
-
<span className="realtime-orb__core" />
|
|
366
|
-
<div className="realtime-orb__canvas">
|
|
367
|
-
<Canvas
|
|
368
|
-
dpr={[1, 2]}
|
|
369
|
-
camera={{ position: [0, 0.85, 1.6], fov: 32 }}
|
|
370
|
-
gl={{ antialias: false, alpha: true, premultipliedAlpha: false }}
|
|
371
|
-
style={{ width: "100%", height: "100%" }}
|
|
372
|
-
>
|
|
373
|
-
<ambientLight intensity={0.6} />
|
|
374
|
-
<RipplePoints
|
|
375
|
-
count={count}
|
|
376
|
-
separation={0.024}
|
|
377
|
-
reducedMotion={reducedMotion}
|
|
378
|
-
levelRef={currentLevelRef}
|
|
379
|
-
speakerRef={currentSpeakerRef}
|
|
380
|
-
/>
|
|
381
|
-
</Canvas>
|
|
382
|
-
</div>
|
|
383
|
-
<span className="realtime-orb__specular" />
|
|
384
|
-
</div>
|
|
385
|
-
)
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
export default RealtimeOrb
|
|
@@ -1,95 +0,0 @@
|
|
|
1
|
-
"use client"
|
|
2
|
-
|
|
3
|
-
// Top-level drop-in chat component. Renders header → (sidebar?) chat-pane,
|
|
4
|
-
// owns `useAgentChat` so the developer only has to pass the endpoint URL.
|
|
5
|
-
//
|
|
6
|
-
// `"use client"` ensures Next.js App Router treats this as a client
|
|
7
|
-
// component — `useAgentChat` calls `fetch` against streaming bodies and
|
|
8
|
-
// holds React state, neither of which is server-renderable.
|
|
9
|
-
|
|
10
|
-
import { useState } from "react"
|
|
11
|
-
import { Composer } from "./Composer"
|
|
12
|
-
import { Header } from "./Header"
|
|
13
|
-
import { RealtimeCallOverlay } from "./RealtimeCallOverlay"
|
|
14
|
-
import { Sidebar } from "./Sidebar"
|
|
15
|
-
import { Transcript } from "./Transcript"
|
|
16
|
-
import { useAgentChat } from "../hooks/useAgentChat"
|
|
17
|
-
import type { TinywebChatProps } from "../types"
|
|
18
|
-
import { themeToStyle } from "../util/theme"
|
|
19
|
-
|
|
20
|
-
export const TinywebChat = (props: TinywebChatProps) => {
|
|
21
|
-
const chat = useAgentChat({
|
|
22
|
-
endpoint: props.endpoint,
|
|
23
|
-
extraBody: props.extraBody,
|
|
24
|
-
headers: props.headers,
|
|
25
|
-
initialMessages: props.initialMessages,
|
|
26
|
-
onEvent: props.onEvent,
|
|
27
|
-
onFinish: props.onFinish,
|
|
28
|
-
})
|
|
29
|
-
|
|
30
|
-
const hasSidebar = Boolean(props.sidebar)
|
|
31
|
-
const mainClass = hasSidebar ? "main" : "main no-sidebar"
|
|
32
|
-
const busy = chat.status === "requesting" || chat.status === "streaming"
|
|
33
|
-
// NOTE: we intentionally do NOT collapse `busy` into `composerDisabled`.
|
|
34
|
-
// Disabling a focused textarea forces the browser to move focus to
|
|
35
|
-
// <body>, breaking the type → enter → keep typing flow. The `busy`
|
|
36
|
-
// flag is forwarded separately so Composer can swap the send → stop
|
|
37
|
-
// button while keeping the textarea editable.
|
|
38
|
-
const composerDisabled = props.disabled === true
|
|
39
|
-
|
|
40
|
-
// Realtime call state. The overlay is mounted ONLY when active so
|
|
41
|
-
// `getUserMedia` / `AudioContext` are not spun up at idle. Plan 0014 §9.
|
|
42
|
-
const [callOpen, setCallOpen] = useState(false)
|
|
43
|
-
const realtime = props.realtime
|
|
44
|
-
|
|
45
|
-
// When a call is active we swap the transcript+composer region with
|
|
46
|
-
// an inline call panel. Keeps the chat layout intact (header +
|
|
47
|
-
// sidebar still visible) — no modal/backdrop. Plan 0014 §9.
|
|
48
|
-
const inCall = Boolean(realtime && callOpen)
|
|
49
|
-
|
|
50
|
-
return (
|
|
51
|
-
<div className="tinyweb-chat" style={themeToStyle(props.theme)}>
|
|
52
|
-
<Header title={props.title ?? "Tinyweb Agent"} />
|
|
53
|
-
<main className={mainClass}>
|
|
54
|
-
<Sidebar>{props.sidebar}</Sidebar>
|
|
55
|
-
<section className="chat">
|
|
56
|
-
{inCall && realtime ? (
|
|
57
|
-
<RealtimeCallOverlay
|
|
58
|
-
tokenEndpoint={realtime.tokenEndpoint}
|
|
59
|
-
tokenHeaders={realtime.tokenHeaders}
|
|
60
|
-
tokenBody={realtime.tokenBody}
|
|
61
|
-
toolHandlers={realtime.toolHandlers}
|
|
62
|
-
toolProxyPath={realtime.toolProxyPath}
|
|
63
|
-
toolProxyHeaders={realtime.toolProxyHeaders}
|
|
64
|
-
idleTimeoutMs={realtime.idleTimeoutMs}
|
|
65
|
-
title={realtime.title ?? props.title}
|
|
66
|
-
onUserTurn={realtime.onUserTurn}
|
|
67
|
-
onAssistantTurn={realtime.onAssistantTurn}
|
|
68
|
-
onClose={() => setCallOpen(false)}
|
|
69
|
-
chat={chat}
|
|
70
|
-
toolRenderers={props.toolRenderers}
|
|
71
|
-
/>
|
|
72
|
-
) : (
|
|
73
|
-
<>
|
|
74
|
-
<Transcript
|
|
75
|
-
nodes={chat.nodes}
|
|
76
|
-
hero={props.hero === undefined ? {} : props.hero}
|
|
77
|
-
toolRenderers={props.toolRenderers}
|
|
78
|
-
status={chat.status}
|
|
79
|
-
/>
|
|
80
|
-
<Composer
|
|
81
|
-
onSend={chat.send}
|
|
82
|
-
disabled={composerDisabled}
|
|
83
|
-
placeholder={props.placeholder}
|
|
84
|
-
attachmentLimits={props.attachmentLimits}
|
|
85
|
-
busy={busy}
|
|
86
|
-
onStop={chat.abort}
|
|
87
|
-
onStartCall={realtime ? () => setCallOpen(true) : undefined}
|
|
88
|
-
/>
|
|
89
|
-
</>
|
|
90
|
-
)}
|
|
91
|
-
</section>
|
|
92
|
-
</main>
|
|
93
|
-
</div>
|
|
94
|
-
)
|
|
95
|
-
}
|
|
@@ -1,146 +0,0 @@
|
|
|
1
|
-
import { useRef } from "react"
|
|
2
|
-
import type { ChatStatus } from "../hooks/useAgentChat"
|
|
3
|
-
import type { ToolRenderer, TranscriptNode } from "../types"
|
|
4
|
-
import { useAnchorLatestUser } from "../hooks/useAnchorLatestUser"
|
|
5
|
-
import { useInitialScrollToEnd } from "../hooks/useInitialScrollToEnd"
|
|
6
|
-
import { friendlyToolLabel } from "../util/tool-labels"
|
|
7
|
-
import { CondensePill } from "./condense/CondensePill"
|
|
8
|
-
import { AssistantMessage } from "./messages/AssistantMessage"
|
|
9
|
-
import { ErrorMessage } from "./messages/ErrorMessage"
|
|
10
|
-
import { ToolMessage } from "./messages/ToolMessage"
|
|
11
|
-
import { UserMessage } from "./messages/UserMessage"
|
|
12
|
-
import { Hero } from "./Hero"
|
|
13
|
-
|
|
14
|
-
export type TranscriptProps = {
|
|
15
|
-
nodes: TranscriptNode[]
|
|
16
|
-
hero?: { title?: string; subtitle?: string } | null
|
|
17
|
-
toolRenderers?: ToolRenderer[]
|
|
18
|
-
/**
|
|
19
|
-
* Optional streaming state from `useAgentChat`. When provided, the
|
|
20
|
-
* transcript renders a "Đang suy nghĩ…" pill while the assistant is
|
|
21
|
-
* preparing the next message but hasn't emitted any visible event yet
|
|
22
|
-
* (covers latency between `send()` and first `text-delta` / `tool-call`,
|
|
23
|
-
* and the gap between `tool-result` and the next `text-delta`).
|
|
24
|
-
*/
|
|
25
|
-
status?: ChatStatus
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
const renderNode = (
|
|
29
|
-
node: TranscriptNode,
|
|
30
|
-
toolRenderers?: ToolRenderer[],
|
|
31
|
-
) => {
|
|
32
|
-
if (node.kind === "user") return <UserMessage content={node.content} images={node.images} />
|
|
33
|
-
if (node.kind === "assistant") return <AssistantMessage content={node.content} />
|
|
34
|
-
if (node.kind === "tool-call") {
|
|
35
|
-
const label = friendlyToolLabel(node.name)
|
|
36
|
-
let rawArgs: string
|
|
37
|
-
try {
|
|
38
|
-
rawArgs = JSON.stringify(node.input ?? {}, null, 2)
|
|
39
|
-
} catch {
|
|
40
|
-
rawArgs = "(unserialisable)"
|
|
41
|
-
}
|
|
42
|
-
return (
|
|
43
|
-
<div className="msg tool-pending">
|
|
44
|
-
<span className="tool-pending-icon" aria-hidden="true">{label.icon}</span>
|
|
45
|
-
<span className="tool-pending-text">{label.verb}…</span>
|
|
46
|
-
<span className="tool-pending-dots" aria-hidden="true">
|
|
47
|
-
<span /><span /><span />
|
|
48
|
-
</span>
|
|
49
|
-
<details className="tool-pending-details">
|
|
50
|
-
<summary>chi tiết</summary>
|
|
51
|
-
<pre>{rawArgs}</pre>
|
|
52
|
-
</details>
|
|
53
|
-
</div>
|
|
54
|
-
)
|
|
55
|
-
}
|
|
56
|
-
if (node.kind === "tool-result") {
|
|
57
|
-
return (
|
|
58
|
-
<ToolMessage
|
|
59
|
-
toolName={node.name}
|
|
60
|
-
result={node.result}
|
|
61
|
-
raw={node.raw}
|
|
62
|
-
toolRenderers={toolRenderers}
|
|
63
|
-
/>
|
|
64
|
-
)
|
|
65
|
-
}
|
|
66
|
-
if (node.kind === "tool-error") {
|
|
67
|
-
return <ErrorMessage label="tool-error" message={node.name + ": " + node.message} />
|
|
68
|
-
}
|
|
69
|
-
if (node.kind === "error") return <ErrorMessage message={node.message} />
|
|
70
|
-
if (node.kind === "condense") return <CondensePill state={node.state} />
|
|
71
|
-
return null
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
const ThinkingPill = () => (
|
|
75
|
-
<span className="tool-pending thinking-pill" data-testid="tinyweb-thinking">
|
|
76
|
-
<span className="tool-pending-icon" aria-hidden="true">💭</span>
|
|
77
|
-
<span className="tool-pending-text">Đang suy nghĩ</span>
|
|
78
|
-
<span className="tool-pending-dots" aria-hidden="true">
|
|
79
|
-
<span /><span /><span />
|
|
80
|
-
</span>
|
|
81
|
-
</span>
|
|
82
|
-
)
|
|
83
|
-
|
|
84
|
-
const shouldShowThinking = (
|
|
85
|
-
status: ChatStatus | undefined,
|
|
86
|
-
nodes: TranscriptNode[],
|
|
87
|
-
): boolean => {
|
|
88
|
-
if (status !== "requesting" && status !== "streaming") return false
|
|
89
|
-
// We only show the pill while waiting for the next visible event. As soon
|
|
90
|
-
// as the assistant is writing text, there's a pending tool-call, an error,
|
|
91
|
-
// or a condense pill, the transcript has its own indicator and we step aside.
|
|
92
|
-
const last = nodes[nodes.length - 1]
|
|
93
|
-
if (!last) return false
|
|
94
|
-
if (last.kind === "user") return true
|
|
95
|
-
if (last.kind === "tool-result") return true
|
|
96
|
-
return false
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
// The id of the latest *user* message — but only when it's the tail of the
|
|
100
|
-
// transcript. We use this to drive `useAnchorLatestUser`: any time the tail
|
|
101
|
-
// flips to a fresh user message we scroll that bubble to the top of the
|
|
102
|
-
// viewport. Returning `null` when the tail is an assistant / tool node keeps
|
|
103
|
-
// the anchor stable while the assistant streams its reply.
|
|
104
|
-
const latestUserTailId = (nodes: TranscriptNode[]): string | null => {
|
|
105
|
-
const last = nodes[nodes.length - 1]
|
|
106
|
-
if (!last) return null
|
|
107
|
-
if (last.kind === "user") return last.id
|
|
108
|
-
return null
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
export const Transcript = (props: TranscriptProps) => {
|
|
112
|
-
const ref = useRef<HTMLDivElement | null>(null)
|
|
113
|
-
const spacerRef = useRef<HTMLDivElement | null>(null)
|
|
114
|
-
// On first mount with non-empty history (e.g. `initialMessages` restored
|
|
115
|
-
// from storage), drop the viewport at the bottom of the transcript so the
|
|
116
|
-
// user lands on the most recent message instead of scrolled back to the
|
|
117
|
-
// very first one. The `nodes.length > 0` signal lets the hook wait if
|
|
118
|
-
// history hydrates asynchronously.
|
|
119
|
-
useInitialScrollToEnd(ref, props.nodes.length > 0)
|
|
120
|
-
useAnchorLatestUser(ref, spacerRef, latestUserTailId(props.nodes))
|
|
121
|
-
const empty = props.nodes.length === 0
|
|
122
|
-
const showHero = empty && props.hero !== null
|
|
123
|
-
const showThinking = shouldShowThinking(props.status, props.nodes)
|
|
124
|
-
// Each node wrapper participates in the flex column so per-message
|
|
125
|
-
// alignment (user→right, assistant→left) works via `align-self` on `.msg`.
|
|
126
|
-
// We also force the wrapper itself to stretch so its child controls width.
|
|
127
|
-
//
|
|
128
|
-
// The trailing `.msg-spacer` is a sentinel: `useAnchorLatestUser` sets its
|
|
129
|
-
// min-height to the container clientHeight so that scrolling the freshly
|
|
130
|
-
// sent user bubble to the top is always possible — even when the assistant
|
|
131
|
-
// reply hasn't yet produced enough content to overflow the viewport.
|
|
132
|
-
return (
|
|
133
|
-
<div className="messages" ref={ref} data-testid="tinyweb-transcript">
|
|
134
|
-
{showHero ? <Hero title={props.hero?.title} subtitle={props.hero?.subtitle} /> : null}
|
|
135
|
-
<div className="messages-inner">
|
|
136
|
-
{props.nodes.map((node) => (
|
|
137
|
-
<div key={node.id} className="msg-row" data-msg-id={node.id}>
|
|
138
|
-
{renderNode(node, props.toolRenderers)}
|
|
139
|
-
</div>
|
|
140
|
-
))}
|
|
141
|
-
{showThinking ? <ThinkingPill /> : null}
|
|
142
|
-
<div ref={spacerRef} className="msg-spacer" aria-hidden="true" />
|
|
143
|
-
</div>
|
|
144
|
-
</div>
|
|
145
|
-
)
|
|
146
|
-
}
|