@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.
- 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 +3243 -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 +3209 -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/{src → dist}/styles.css +29 -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
|
@@ -1,454 +0,0 @@
|
|
|
1
|
-
// useAgentChat — top-level state machine for the chat UI.
|
|
2
|
-
//
|
|
3
|
-
// Owns:
|
|
4
|
-
// - The transcript array (mix of user / assistant / tool / condense rows
|
|
5
|
-
// in chronological order).
|
|
6
|
-
// - The streaming state ("idle" → "requesting" → "streaming" → "finished").
|
|
7
|
-
// - A single in-flight fetch + `AbortController` so callers can cancel.
|
|
8
|
-
//
|
|
9
|
-
// The chronological ordering rule (port of the `turnState` cursor at
|
|
10
|
-
// [`app.js`](../../../../examples/device-pilot/public/app.js:442)): when a
|
|
11
|
-
// tool / condense / error event arrives we "close" the active assistant
|
|
12
|
-
// row, so the next `text-delta` opens a fresh row. This preserves the
|
|
13
|
-
// real interleaving instead of bunching all assistant text together.
|
|
14
|
-
|
|
15
|
-
import { useCallback, useEffect, useRef, useState } from "react"
|
|
16
|
-
import type { AgentEvent, FinishEvent } from "@tinyweb-agent-framework/protocol"
|
|
17
|
-
import type { ChatMessage, CondenseState, ImageAttachment, TranscriptNode } from "../types"
|
|
18
|
-
import { parseNdjsonStream } from "./useNdjsonStream"
|
|
19
|
-
|
|
20
|
-
export type SendOptions = { readonly images?: ReadonlyArray<ImageAttachment> }
|
|
21
|
-
|
|
22
|
-
const stripPreview = (img: ImageAttachment) => ({
|
|
23
|
-
type: img.type,
|
|
24
|
-
mediaType: img.mediaType,
|
|
25
|
-
data: img.data,
|
|
26
|
-
url: img.url,
|
|
27
|
-
filename: img.filename,
|
|
28
|
-
})
|
|
29
|
-
|
|
30
|
-
export type ChatStatus = "idle" | "requesting" | "streaming" | "finished" | "error"
|
|
31
|
-
|
|
32
|
-
export type UseAgentChatOptions = {
|
|
33
|
-
endpoint: string
|
|
34
|
-
extraBody?: Record<string, unknown> | (() => Record<string, unknown>)
|
|
35
|
-
headers?: HeadersInit | (() => HeadersInit)
|
|
36
|
-
initialMessages?: ChatMessage[]
|
|
37
|
-
onEvent?: (event: AgentEvent) => void
|
|
38
|
-
onFinish?: (event: FinishEvent) => void
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
export type UseAgentChatReturn = {
|
|
42
|
-
nodes: TranscriptNode[]
|
|
43
|
-
status: ChatStatus
|
|
44
|
-
errorMessage: string | undefined
|
|
45
|
-
send: (prompt: string, options?: SendOptions) => void
|
|
46
|
-
abort: () => void
|
|
47
|
-
reset: () => void
|
|
48
|
-
/**
|
|
49
|
-
* Inject an `AgentEvent` into the transcript as if it had streamed
|
|
50
|
-
* from the chat endpoint. Used by the realtime call overlay to push
|
|
51
|
-
* voice turns + tool calls into the same history the text chat sees,
|
|
52
|
-
* so the right-side debug sidebar can render them with the standard
|
|
53
|
-
* tool renderers. The event runs through the exact same state machine
|
|
54
|
-
* `send()` uses, including the `openAssistantRef` cursor.
|
|
55
|
-
*/
|
|
56
|
-
applyEvent: (event: AgentEvent) => void
|
|
57
|
-
/**
|
|
58
|
-
* Push a user-authored message directly into the transcript without
|
|
59
|
-
* dispatching a fetch. Used by the realtime overlay to record voice
|
|
60
|
-
* turns (transcribed by the LLM) into the same nodes array as text
|
|
61
|
-
* messages, so the chat history stays unified across modalities.
|
|
62
|
-
*
|
|
63
|
-
* If an assistant node is currently streaming (open cursor), the new
|
|
64
|
-
* user node is spliced in BEFORE it — this matters for realtime voice
|
|
65
|
-
* where the agent may begin replying (and emitting `text-delta`)
|
|
66
|
-
* before the user's `inputTranscription` finishes streaming. Without
|
|
67
|
-
* this, the user bubble would render AFTER the agent's reply.
|
|
68
|
-
*/
|
|
69
|
-
appendUserMessage: (content: string, images?: ReadonlyArray<ImageAttachment>) => void
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
let nodeCounter = 0
|
|
73
|
-
const nextNodeId = (): string => {
|
|
74
|
-
nodeCounter += 1
|
|
75
|
-
return "n" + nodeCounter
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
const initialNodes = (msgs: ChatMessage[] | undefined): TranscriptNode[] => {
|
|
79
|
-
if (!msgs) return []
|
|
80
|
-
return msgs.map((m) =>
|
|
81
|
-
m.role === "user"
|
|
82
|
-
? { kind: "user", id: nextNodeId(), content: m.content, images: m.images }
|
|
83
|
-
: { kind: "assistant", id: nextNodeId(), content: m.content },
|
|
84
|
-
)
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
const resolveBody = (extra: UseAgentChatOptions["extraBody"]): Record<string, unknown> => {
|
|
88
|
-
if (typeof extra === "function") return extra()
|
|
89
|
-
if (extra) return extra
|
|
90
|
-
return {}
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
const resolveHeaders = (h: UseAgentChatOptions["headers"]): HeadersInit | undefined => {
|
|
94
|
-
if (typeof h === "function") return h()
|
|
95
|
-
return h
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
export const useAgentChat = (opts: UseAgentChatOptions): UseAgentChatReturn => {
|
|
99
|
-
const [nodes, setNodes] = useState<TranscriptNode[]>(() => initialNodes(opts.initialMessages))
|
|
100
|
-
const [status, setStatus] = useState<ChatStatus>("idle")
|
|
101
|
-
const [errorMessage, setErrorMessage] = useState<string | undefined>(undefined)
|
|
102
|
-
const abortRef = useRef<AbortController | null>(null)
|
|
103
|
-
// Track the open assistant bubble id per turn so text-delta events accumulate
|
|
104
|
-
// into the right node. Reset to null on tool / condense / error events.
|
|
105
|
-
const openAssistantRef = useRef<string | null>(null)
|
|
106
|
-
|
|
107
|
-
// Stash callbacks in refs so the send() closure stays stable across
|
|
108
|
-
// re-renders while still calling the latest version.
|
|
109
|
-
const onEventRef = useRef(opts.onEvent)
|
|
110
|
-
const onFinishRef = useRef(opts.onFinish)
|
|
111
|
-
onEventRef.current = opts.onEvent
|
|
112
|
-
onFinishRef.current = opts.onFinish
|
|
113
|
-
|
|
114
|
-
// Capture the latest extra-body / headers callbacks too.
|
|
115
|
-
const extraBodyRef = useRef(opts.extraBody)
|
|
116
|
-
const headersRef = useRef(opts.headers)
|
|
117
|
-
extraBodyRef.current = opts.extraBody
|
|
118
|
-
headersRef.current = opts.headers
|
|
119
|
-
|
|
120
|
-
const endpointRef = useRef(opts.endpoint)
|
|
121
|
-
endpointRef.current = opts.endpoint
|
|
122
|
-
|
|
123
|
-
useEffect(
|
|
124
|
-
() => () => {
|
|
125
|
-
// Abort on unmount so the dangling fetch doesn't keep pushing into
|
|
126
|
-
// a torn-down component.
|
|
127
|
-
abortRef.current?.abort()
|
|
128
|
-
},
|
|
129
|
-
[],
|
|
130
|
-
)
|
|
131
|
-
|
|
132
|
-
const applyEvent = useCallback((ev: AgentEvent) => {
|
|
133
|
-
onEventRef.current?.(ev)
|
|
134
|
-
if (ev.type === "text-delta") {
|
|
135
|
-
setNodes((prev) => {
|
|
136
|
-
const openId = openAssistantRef.current
|
|
137
|
-
if (openId) {
|
|
138
|
-
return prev.map((n) =>
|
|
139
|
-
n.id === openId && n.kind === "assistant"
|
|
140
|
-
? { ...n, content: n.content + ev.text }
|
|
141
|
-
: n,
|
|
142
|
-
)
|
|
143
|
-
}
|
|
144
|
-
const id = nextNodeId()
|
|
145
|
-
openAssistantRef.current = id
|
|
146
|
-
return prev.concat({ kind: "assistant", id, content: ev.text })
|
|
147
|
-
})
|
|
148
|
-
return
|
|
149
|
-
}
|
|
150
|
-
if (ev.type === "text-end") {
|
|
151
|
-
openAssistantRef.current = null
|
|
152
|
-
return
|
|
153
|
-
}
|
|
154
|
-
if (ev.type === "reasoning-delta") {
|
|
155
|
-
// Reasoning rendering is out of scope for v0 — surface via onEvent
|
|
156
|
-
// but don't push into the transcript.
|
|
157
|
-
return
|
|
158
|
-
}
|
|
159
|
-
if (ev.type === "tool-call") {
|
|
160
|
-
openAssistantRef.current = null
|
|
161
|
-
setNodes((prev) =>
|
|
162
|
-
prev.concat({
|
|
163
|
-
kind: "tool-call",
|
|
164
|
-
id: nextNodeId(),
|
|
165
|
-
callId: ev.id,
|
|
166
|
-
name: ev.name,
|
|
167
|
-
input: ev.input,
|
|
168
|
-
}),
|
|
169
|
-
)
|
|
170
|
-
return
|
|
171
|
-
}
|
|
172
|
-
if (ev.type === "tool-result") {
|
|
173
|
-
openAssistantRef.current = null
|
|
174
|
-
setNodes((prev) =>
|
|
175
|
-
// Drop the matching pending `tool-call` row so the result card
|
|
176
|
-
// replaces it inline instead of stacking a stale "Đang …" pill above.
|
|
177
|
-
prev
|
|
178
|
-
.filter((n) => !(n.kind === "tool-call" && n.callId === ev.id))
|
|
179
|
-
.concat({
|
|
180
|
-
kind: "tool-result",
|
|
181
|
-
id: nextNodeId(),
|
|
182
|
-
name: ev.name,
|
|
183
|
-
result: ev.result,
|
|
184
|
-
raw: ev,
|
|
185
|
-
}),
|
|
186
|
-
)
|
|
187
|
-
return
|
|
188
|
-
}
|
|
189
|
-
if (ev.type === "tool-error") {
|
|
190
|
-
openAssistantRef.current = null
|
|
191
|
-
setNodes((prev) =>
|
|
192
|
-
prev
|
|
193
|
-
.filter((n) => !(n.kind === "tool-call" && n.callId === ev.id))
|
|
194
|
-
.concat({
|
|
195
|
-
kind: "tool-error",
|
|
196
|
-
id: nextNodeId(),
|
|
197
|
-
name: ev.name,
|
|
198
|
-
message: ev.message,
|
|
199
|
-
}),
|
|
200
|
-
)
|
|
201
|
-
return
|
|
202
|
-
}
|
|
203
|
-
if (ev.type === "context-condense-start") {
|
|
204
|
-
openAssistantRef.current = null
|
|
205
|
-
setNodes((prev) =>
|
|
206
|
-
prev.concat({
|
|
207
|
-
kind: "condense",
|
|
208
|
-
id: nextNodeId(),
|
|
209
|
-
trigger: ev.trigger,
|
|
210
|
-
state: {
|
|
211
|
-
phase: "start",
|
|
212
|
-
trigger: ev.trigger,
|
|
213
|
-
estimatedTokens: ev.estimatedTokens,
|
|
214
|
-
budgetTokens: ev.budgetTokens,
|
|
215
|
-
},
|
|
216
|
-
}),
|
|
217
|
-
)
|
|
218
|
-
return
|
|
219
|
-
}
|
|
220
|
-
if (ev.type === "context-condense") {
|
|
221
|
-
openAssistantRef.current = null
|
|
222
|
-
setNodes((prev) => updateCondense(prev, ev.trigger, {
|
|
223
|
-
phase: "success",
|
|
224
|
-
trigger: ev.trigger,
|
|
225
|
-
summary: ev.summary,
|
|
226
|
-
prevTokens: ev.prevTokens,
|
|
227
|
-
newTokens: ev.newTokens,
|
|
228
|
-
cost: ev.cost,
|
|
229
|
-
modelId: ev.modelId,
|
|
230
|
-
}))
|
|
231
|
-
return
|
|
232
|
-
}
|
|
233
|
-
if (ev.type === "context-condense-error") {
|
|
234
|
-
openAssistantRef.current = null
|
|
235
|
-
setNodes((prev) => updateCondense(prev, ev.trigger, {
|
|
236
|
-
phase: "error",
|
|
237
|
-
trigger: ev.trigger,
|
|
238
|
-
message: ev.message,
|
|
239
|
-
retryExhausted: ev.retryExhausted,
|
|
240
|
-
}))
|
|
241
|
-
return
|
|
242
|
-
}
|
|
243
|
-
if (ev.type === "error") {
|
|
244
|
-
openAssistantRef.current = null
|
|
245
|
-
setNodes((prev) =>
|
|
246
|
-
prev.concat({ kind: "error", id: nextNodeId(), message: ev.message }),
|
|
247
|
-
)
|
|
248
|
-
return
|
|
249
|
-
}
|
|
250
|
-
if (ev.type === "finish") {
|
|
251
|
-
onFinishRef.current?.(ev)
|
|
252
|
-
return
|
|
253
|
-
}
|
|
254
|
-
// step-finish: drop — only relevant for analytics via onEvent.
|
|
255
|
-
}, [])
|
|
256
|
-
|
|
257
|
-
const send = useCallback(
|
|
258
|
-
(rawPrompt: string, options?: SendOptions) => {
|
|
259
|
-
const prompt = rawPrompt.trim()
|
|
260
|
-
const images = options?.images ?? []
|
|
261
|
-
if (!prompt && images.length === 0) return
|
|
262
|
-
if (status === "requesting" || status === "streaming") {
|
|
263
|
-
console.warn("[tinyweb-chat] send() called while a request is in flight — ignored")
|
|
264
|
-
return
|
|
265
|
-
}
|
|
266
|
-
setErrorMessage(undefined)
|
|
267
|
-
openAssistantRef.current = null
|
|
268
|
-
setNodes((prev) =>
|
|
269
|
-
prev.concat({
|
|
270
|
-
kind: "user",
|
|
271
|
-
id: nextNodeId(),
|
|
272
|
-
content: prompt,
|
|
273
|
-
images: images.length > 0 ? images : undefined,
|
|
274
|
-
}),
|
|
275
|
-
)
|
|
276
|
-
|
|
277
|
-
const ctrl = new AbortController()
|
|
278
|
-
abortRef.current = ctrl
|
|
279
|
-
setStatus("requesting")
|
|
280
|
-
|
|
281
|
-
const wireAttachments = images.map(stripPreview)
|
|
282
|
-
const body = JSON.stringify({
|
|
283
|
-
prompt,
|
|
284
|
-
...(wireAttachments.length > 0 ? { attachments: wireAttachments } : {}),
|
|
285
|
-
...resolveBody(extraBodyRef.current),
|
|
286
|
-
})
|
|
287
|
-
const baseHeaders: Record<string, string> = { "content-type": "application/json" }
|
|
288
|
-
const merged = new Headers(baseHeaders)
|
|
289
|
-
const extra = resolveHeaders(headersRef.current)
|
|
290
|
-
if (extra) {
|
|
291
|
-
new Headers(extra).forEach((v, k) => merged.set(k, v))
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
const run = async () => {
|
|
295
|
-
try {
|
|
296
|
-
const res = await fetch(endpointRef.current, {
|
|
297
|
-
method: "POST",
|
|
298
|
-
headers: merged,
|
|
299
|
-
body,
|
|
300
|
-
signal: ctrl.signal,
|
|
301
|
-
})
|
|
302
|
-
if (!res.ok || !res.body) {
|
|
303
|
-
const txt = await res.text().catch(() => "")
|
|
304
|
-
throw new Error("chat failed: " + res.status + " " + txt)
|
|
305
|
-
}
|
|
306
|
-
setStatus("streaming")
|
|
307
|
-
for await (const ev of parseNdjsonStream(res.body)) {
|
|
308
|
-
if (ctrl.signal.aborted) break
|
|
309
|
-
applyEvent(ev)
|
|
310
|
-
}
|
|
311
|
-
setStatus("finished")
|
|
312
|
-
} catch (err) {
|
|
313
|
-
if (ctrl.signal.aborted) {
|
|
314
|
-
setStatus("idle")
|
|
315
|
-
return
|
|
316
|
-
}
|
|
317
|
-
const msg = err instanceof Error ? err.message : String(err)
|
|
318
|
-
setErrorMessage(msg)
|
|
319
|
-
setNodes((prev) => prev.concat({ kind: "error", id: nextNodeId(), message: msg }))
|
|
320
|
-
setStatus("error")
|
|
321
|
-
} finally {
|
|
322
|
-
openAssistantRef.current = null
|
|
323
|
-
if (abortRef.current === ctrl) abortRef.current = null
|
|
324
|
-
}
|
|
325
|
-
}
|
|
326
|
-
void run()
|
|
327
|
-
},
|
|
328
|
-
[applyEvent, status],
|
|
329
|
-
)
|
|
330
|
-
|
|
331
|
-
const abort = useCallback(() => {
|
|
332
|
-
abortRef.current?.abort()
|
|
333
|
-
}, [])
|
|
334
|
-
|
|
335
|
-
const reset = useCallback(() => {
|
|
336
|
-
abortRef.current?.abort()
|
|
337
|
-
openAssistantRef.current = null
|
|
338
|
-
setNodes(initialNodes(opts.initialMessages))
|
|
339
|
-
setStatus("idle")
|
|
340
|
-
setErrorMessage(undefined)
|
|
341
|
-
}, [opts.initialMessages])
|
|
342
|
-
|
|
343
|
-
const appendUserMessage = useCallback(
|
|
344
|
-
(content: string, images?: ReadonlyArray<ImageAttachment>) => {
|
|
345
|
-
// In realtime voice, the agent may start streaming its reply
|
|
346
|
-
// (opening an assistant node via `text-delta`) AND/OR invoke
|
|
347
|
-
// tools BEFORE the user's `inputTranscription` finalises —
|
|
348
|
-
// Gemini Live runs input transcription / output transcription
|
|
349
|
-
// / tool routing in parallel. If we naively `concat` the user
|
|
350
|
-
// node here, it lands AFTER any combination of trailing
|
|
351
|
-
// `assistant`, `tool-call`, `tool-result`, `tool-error` nodes
|
|
352
|
-
// that were materialised in response to this same voice turn,
|
|
353
|
-
// producing the visible reversal documented in Bug 0006:
|
|
354
|
-
//
|
|
355
|
-
// tool-call card → user bubble → assistant answer (WRONG)
|
|
356
|
-
//
|
|
357
|
-
// Fix: walk backward from the end of the transcript and find
|
|
358
|
-
// the first node in the trailing "agent reaction" run, where
|
|
359
|
-
// a "reaction" node is one of: `assistant` / `tool-call` /
|
|
360
|
-
// `tool-result` / `tool-error`. Splice the user node BEFORE
|
|
361
|
-
// that index so the order becomes:
|
|
362
|
-
//
|
|
363
|
-
// user → assistant(thinking) → tool-call → tool-result →
|
|
364
|
-
// assistant(answer) (RIGHT)
|
|
365
|
-
//
|
|
366
|
-
// Other node kinds (`condense`, `error`, prior `user`) break
|
|
367
|
-
// the walk so older turns aren't disturbed.
|
|
368
|
-
const openId = openAssistantRef.current
|
|
369
|
-
const isReactionKind = (
|
|
370
|
-
k: TranscriptNode["kind"],
|
|
371
|
-
): k is "assistant" | "tool-call" | "tool-result" | "tool-error" =>
|
|
372
|
-
k === "assistant" || k === "tool-call" || k === "tool-result" || k === "tool-error"
|
|
373
|
-
setNodes((prev) => {
|
|
374
|
-
const userNode: TranscriptNode = {
|
|
375
|
-
kind: "user",
|
|
376
|
-
id: nextNodeId(),
|
|
377
|
-
content,
|
|
378
|
-
images: images && images.length > 0 ? images : undefined,
|
|
379
|
-
}
|
|
380
|
-
// Walk backward to find the start of the trailing reaction
|
|
381
|
-
// run (assistant / tool-* nodes that belong to the CURRENT
|
|
382
|
-
// voice turn). This handles all of:
|
|
383
|
-
// 1. open cursor present (`openAssistantRef.current` set) —
|
|
384
|
-
// the trailing run includes the open assistant node.
|
|
385
|
-
// 2. agent-transcript-final closed the cursor moments
|
|
386
|
-
// before user-transcript-final arrived.
|
|
387
|
-
// 3. tool-call / tool-result inserted after a partial
|
|
388
|
-
// assistant "thinking" turn but before the user-final.
|
|
389
|
-
// 4. multiple consecutive assistant turns / tool calls
|
|
390
|
-
// before the user's input transcription finalises.
|
|
391
|
-
//
|
|
392
|
-
// The run stops as soon as we hit a non-reaction node (e.g.
|
|
393
|
-
// a prior `user` bubble — turn boundary) OR an `assistant`
|
|
394
|
-
// that is itself immediately preceded by a `user` (this is
|
|
395
|
-
// the completed answer of a PREVIOUS turn, not part of the
|
|
396
|
-
// current reaction run).
|
|
397
|
-
let insertAt = prev.length
|
|
398
|
-
for (let i = prev.length - 1; i >= 0; i--) {
|
|
399
|
-
const n = prev[i]
|
|
400
|
-
if (!n || !isReactionKind(n.kind)) break
|
|
401
|
-
// If this assistant node is preceded by a `user`, it's the
|
|
402
|
-
// tail of an OLDER completed turn (the natural `[user,
|
|
403
|
-
// assistant]` pair), not part of the trailing reaction run
|
|
404
|
-
// we want to push the new user node BEFORE. Stop here so
|
|
405
|
-
// older turns stay untouched — do NOT update `insertAt`.
|
|
406
|
-
const prevNode = i > 0 ? prev[i - 1] : undefined
|
|
407
|
-
if (n.kind === "assistant" && prevNode && prevNode.kind === "user") break
|
|
408
|
-
insertAt = i
|
|
409
|
-
}
|
|
410
|
-
// Safety: if we have an explicit open-cursor id, prefer the
|
|
411
|
-
// earlier of the two anchors. The cursor id never lies about
|
|
412
|
-
// which assistant bubble is currently streaming, and the
|
|
413
|
-
// trailing-run walk may stop short if a non-reaction node
|
|
414
|
-
// (e.g. a stale `error`) sneaks in between.
|
|
415
|
-
if (openId) {
|
|
416
|
-
const cursorIdx = prev.findIndex(
|
|
417
|
-
(n) => n.id === openId && n.kind === "assistant",
|
|
418
|
-
)
|
|
419
|
-
if (cursorIdx >= 0 && cursorIdx < insertAt) insertAt = cursorIdx
|
|
420
|
-
}
|
|
421
|
-
if (insertAt < prev.length) {
|
|
422
|
-
const next = prev.slice()
|
|
423
|
-
next.splice(insertAt, 0, userNode)
|
|
424
|
-
return next
|
|
425
|
-
}
|
|
426
|
-
return prev.concat(userNode)
|
|
427
|
-
})
|
|
428
|
-
},
|
|
429
|
-
[],
|
|
430
|
-
)
|
|
431
|
-
|
|
432
|
-
return { nodes, status, errorMessage, send, abort, reset, applyEvent, appendUserMessage }
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
const updateCondense = (
|
|
436
|
-
prev: TranscriptNode[],
|
|
437
|
-
trigger: string,
|
|
438
|
-
next: CondenseState,
|
|
439
|
-
): TranscriptNode[] => {
|
|
440
|
-
const existingIdx = prev.findIndex(
|
|
441
|
-
(n) => n.kind === "condense" && n.trigger === trigger,
|
|
442
|
-
)
|
|
443
|
-
if (existingIdx >= 0) {
|
|
444
|
-
const copy = prev.slice()
|
|
445
|
-
const node = copy[existingIdx]
|
|
446
|
-
if (node && node.kind === "condense") {
|
|
447
|
-
copy[existingIdx] = { ...node, state: next }
|
|
448
|
-
}
|
|
449
|
-
return copy
|
|
450
|
-
}
|
|
451
|
-
// No matching start — render the success/error as its own pill so the
|
|
452
|
-
// event isn't lost on out-of-order replay.
|
|
453
|
-
return prev.concat({ kind: "condense", id: nextNodeId(), trigger, state: next })
|
|
454
|
-
}
|
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
// Anchor-to-latest-user autoscroll.
|
|
2
|
-
//
|
|
3
|
-
// UX target: when the user sends a new message, scroll the transcript so that
|
|
4
|
-
// the freshly-sent user bubble sits at the *top* of the viewport — the same
|
|
5
|
-
// pattern ChatGPT / Claude use. The assistant reply then streams in below
|
|
6
|
-
// without yanking the viewport around. Unlike the previous stick-to-bottom
|
|
7
|
-
// behaviour, we do NOT chase the bottom while the assistant is writing; the
|
|
8
|
-
// user stays anchored on what they just asked.
|
|
9
|
-
//
|
|
10
|
-
// Implementation notes
|
|
11
|
-
// --------------------
|
|
12
|
-
//
|
|
13
|
-
// * The hook watches the *last* node id. Each render it compares to the last
|
|
14
|
-
// id we anchored on; when it changes AND the new tail is a user message,
|
|
15
|
-
// we look up the matching `[data-msg-id="…"]` row inside the scroll
|
|
16
|
-
// container and scroll it to the top (`block: "start"`).
|
|
17
|
-
//
|
|
18
|
-
// * A spacer is rendered after the messages so there is always enough room
|
|
19
|
-
// to push the user bubble to the top, even when the assistant hasn't yet
|
|
20
|
-
// produced enough content to fill the viewport. The spacer height is the
|
|
21
|
-
// container's clientHeight minus a small padding allowance, recomputed on
|
|
22
|
-
// resize. Without this, a short transcript can't scroll at all and the
|
|
23
|
-
// user message stays mid-screen.
|
|
24
|
-
|
|
25
|
-
import { useEffect, useLayoutEffect, useRef, type RefObject } from "react"
|
|
26
|
-
|
|
27
|
-
const SCROLL_PADDING_TOP_PX = 16
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Scroll `containerRef`'s element so the most recently added user message is
|
|
31
|
-
* pinned to the top whenever a new user message arrives.
|
|
32
|
-
*
|
|
33
|
-
* @param containerRef Ref to the scroll container (typically `.messages`).
|
|
34
|
-
* @param spacerRef Ref to a sentinel element rendered at the end of the
|
|
35
|
-
* transcript; its `min-height` is kept in sync with the container so the
|
|
36
|
-
* user bubble can always reach the top.
|
|
37
|
-
* @param latestUserId The id of the latest user message in the transcript,
|
|
38
|
-
* or `null` when the tail isn't a user message. Changing this id is what
|
|
39
|
-
* triggers a re-anchor.
|
|
40
|
-
*/
|
|
41
|
-
export const useAnchorLatestUser = (
|
|
42
|
-
containerRef: RefObject<HTMLElement | null>,
|
|
43
|
-
spacerRef: RefObject<HTMLElement | null>,
|
|
44
|
-
latestUserId: string | null,
|
|
45
|
-
): void => {
|
|
46
|
-
// Snapshot the `latestUserId` value at the moment this hook is first called.
|
|
47
|
-
// Anything matching this snapshot is considered "already on screen at mount"
|
|
48
|
-
// and must NOT trigger an anchor scroll (defer to `useInitialScrollToEnd`).
|
|
49
|
-
// Anything different is a *new* user message → scroll it to the top.
|
|
50
|
-
//
|
|
51
|
-
// Using a ref initialized lazily on first render keeps the snapshot stable
|
|
52
|
-
// across re-renders without needing a state.
|
|
53
|
-
const initialIdRef = useRef<{ value: string | null } | null>(null)
|
|
54
|
-
if (initialIdRef.current === null) {
|
|
55
|
-
initialIdRef.current = { value: latestUserId }
|
|
56
|
-
}
|
|
57
|
-
const anchoredIdRef = useRef<string | null>(initialIdRef.current.value)
|
|
58
|
-
|
|
59
|
-
// Keep the spacer tall enough that scrolling the latest user message to the
|
|
60
|
-
// top is always possible. Recomputed on container resize.
|
|
61
|
-
useEffect(() => {
|
|
62
|
-
const container = containerRef.current
|
|
63
|
-
const spacer = spacerRef.current
|
|
64
|
-
if (!container || !spacer) return
|
|
65
|
-
const sync = () => {
|
|
66
|
-
const h = container.clientHeight - SCROLL_PADDING_TOP_PX
|
|
67
|
-
spacer.style.minHeight = (h > 0 ? h : 0) + "px"
|
|
68
|
-
}
|
|
69
|
-
sync()
|
|
70
|
-
const RO = (globalThis as { ResizeObserver?: typeof ResizeObserver }).ResizeObserver
|
|
71
|
-
if (!RO) return
|
|
72
|
-
const ro = new RO(sync)
|
|
73
|
-
ro.observe(container)
|
|
74
|
-
return () => ro.disconnect()
|
|
75
|
-
}, [containerRef, spacerRef])
|
|
76
|
-
|
|
77
|
-
// Anchor on every new user message. `useLayoutEffect` so the scroll lands
|
|
78
|
-
// in the same frame the new bubble paints — no visible jump.
|
|
79
|
-
useLayoutEffect(() => {
|
|
80
|
-
if (latestUserId === null) return
|
|
81
|
-
// Mount-time id (restored transcript already ending on a user message):
|
|
82
|
-
// skip — `useInitialScrollToEnd` is responsible for placing the viewport.
|
|
83
|
-
const initial = initialIdRef.current
|
|
84
|
-
if (initial && initial.value !== null && latestUserId === initial.value) {
|
|
85
|
-
anchoredIdRef.current = latestUserId
|
|
86
|
-
return
|
|
87
|
-
}
|
|
88
|
-
if (anchoredIdRef.current === latestUserId) return
|
|
89
|
-
const container = containerRef.current
|
|
90
|
-
if (!container) return
|
|
91
|
-
const row = container.querySelector<HTMLElement>(
|
|
92
|
-
`[data-msg-id="${CSS.escape(latestUserId)}"]`,
|
|
93
|
-
)
|
|
94
|
-
if (!row) return
|
|
95
|
-
const top = row.offsetTop - SCROLL_PADDING_TOP_PX
|
|
96
|
-
container.scrollTo({ top: top > 0 ? top : 0, behavior: "smooth" })
|
|
97
|
-
anchoredIdRef.current = latestUserId
|
|
98
|
-
}, [containerRef, latestUserId])
|
|
99
|
-
}
|
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
// On first mount, jump the transcript scroll position to the end so the
|
|
2
|
-
// most recent message is visible. This matches user expectation when
|
|
3
|
-
// re-opening a chat: you should land near the bottom of the conversation,
|
|
4
|
-
// not at the top scrolled back through history.
|
|
5
|
-
//
|
|
6
|
-
// We deliberately do this exactly once — only on the first commit where
|
|
7
|
-
// the container has measurable content. Subsequent re-anchoring (e.g.
|
|
8
|
-
// scrolling the latest user message to the top after `send()`) is handled
|
|
9
|
-
// by `useAnchorLatestUser` and must not be overridden by this hook.
|
|
10
|
-
|
|
11
|
-
import { useLayoutEffect, useRef, type RefObject } from "react"
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* Scroll `containerRef`'s element to the very bottom on first mount,
|
|
15
|
-
* without animation. Re-runs only if the container hadn't produced any
|
|
16
|
-
* scrollable height on the first commit (e.g. content hydrated later);
|
|
17
|
-
* once we successfully scroll once, the hook becomes a no-op for the
|
|
18
|
-
* lifetime of the component.
|
|
19
|
-
*
|
|
20
|
-
* @param containerRef Ref to the scroll container (typically `.messages`).
|
|
21
|
-
* @param ready Optional signal — when provided, the initial scroll only
|
|
22
|
-
* fires once `ready` is truthy. Useful when the transcript starts empty
|
|
23
|
-
* and the hook must wait for `initialMessages` to be applied.
|
|
24
|
-
*/
|
|
25
|
-
export const useInitialScrollToEnd = (
|
|
26
|
-
containerRef: RefObject<HTMLElement | null>,
|
|
27
|
-
ready: unknown,
|
|
28
|
-
): void => {
|
|
29
|
-
const doneRef = useRef(false)
|
|
30
|
-
|
|
31
|
-
useLayoutEffect(() => {
|
|
32
|
-
if (doneRef.current) return
|
|
33
|
-
const el = containerRef.current
|
|
34
|
-
if (!el) return
|
|
35
|
-
// Wait until there's actual scrollable content; on an empty transcript
|
|
36
|
-
// there's nothing to land on. Fire on the next dep change instead.
|
|
37
|
-
if (el.scrollHeight <= el.clientHeight) return
|
|
38
|
-
el.scrollTop = el.scrollHeight
|
|
39
|
-
doneRef.current = true
|
|
40
|
-
}, [containerRef, ready])
|
|
41
|
-
}
|
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
// NDJSON parser for AgentEvent streams.
|
|
2
|
-
//
|
|
3
|
-
// The server emits one JSON object per `\n`-terminated line. Two wrinkles:
|
|
4
|
-
// - Keepalive comment lines start with `:` (mirrors the SSE convention).
|
|
5
|
-
// The server uses these to keep the proxy from closing the socket on
|
|
6
|
-
// idle channels.
|
|
7
|
-
// - Chunks from `ReadableStreamDefaultReader<Uint8Array>` may split a
|
|
8
|
-
// single JSON object across multiple reads. We buffer the tail until
|
|
9
|
-
// we see a newline.
|
|
10
|
-
//
|
|
11
|
-
// Implemented as a plain async generator so tests can feed it a synthetic
|
|
12
|
-
// `ReadableStream` without dragging in React.
|
|
13
|
-
|
|
14
|
-
import { isAgentEvent, type AgentEvent } from "@tinyweb-agent-framework/protocol"
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* Parses an NDJSON `ReadableStream<Uint8Array>` into validated `AgentEvent`
|
|
18
|
-
* values. Invalid JSON lines, keepalive comments, and events that don't
|
|
19
|
-
* match the protocol schema are silently dropped.
|
|
20
|
-
*
|
|
21
|
-
* Caller is responsible for cancelling the stream (e.g. via the `AbortSignal`
|
|
22
|
-
* passed to the originating `fetch`).
|
|
23
|
-
*/
|
|
24
|
-
export async function* parseNdjsonStream(
|
|
25
|
-
stream: ReadableStream<Uint8Array>,
|
|
26
|
-
): AsyncGenerator<AgentEvent, void, void> {
|
|
27
|
-
const reader = stream.getReader()
|
|
28
|
-
const decoder = new TextDecoder()
|
|
29
|
-
let buf = ""
|
|
30
|
-
|
|
31
|
-
while (true) {
|
|
32
|
-
const chunk = await reader.read()
|
|
33
|
-
if (chunk.done) break
|
|
34
|
-
buf += decoder.decode(chunk.value, { stream: true })
|
|
35
|
-
|
|
36
|
-
let idx = buf.indexOf("\n")
|
|
37
|
-
while (idx >= 0) {
|
|
38
|
-
const line = buf.slice(0, idx).trim()
|
|
39
|
-
buf = buf.slice(idx + 1)
|
|
40
|
-
idx = buf.indexOf("\n")
|
|
41
|
-
if (!line) continue
|
|
42
|
-
if (line.startsWith(":")) continue // keepalive comment
|
|
43
|
-
const parsed = safeParse(line)
|
|
44
|
-
if (parsed === undefined) continue
|
|
45
|
-
if (!isAgentEvent(parsed)) {
|
|
46
|
-
// Drop silently — server may evolve the schema; we don't want
|
|
47
|
-
// unknown event types to crash the chat. A warn surfaces it in
|
|
48
|
-
// devtools without blocking the stream.
|
|
49
|
-
console.warn("[tinyweb-chat] dropping non-AgentEvent line", parsed)
|
|
50
|
-
continue
|
|
51
|
-
}
|
|
52
|
-
yield parsed
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
// Flush whatever's left after the producer closes — typical when the
|
|
57
|
-
// last line doesn't end with a newline.
|
|
58
|
-
const tail = buf.trim()
|
|
59
|
-
if (tail && !tail.startsWith(":")) {
|
|
60
|
-
const parsed = safeParse(tail)
|
|
61
|
-
if (parsed !== undefined && isAgentEvent(parsed)) yield parsed
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
const safeParse = (line: string): unknown => {
|
|
66
|
-
try {
|
|
67
|
-
return JSON.parse(line)
|
|
68
|
-
} catch {
|
|
69
|
-
return undefined
|
|
70
|
-
}
|
|
71
|
-
}
|