devnonla-ui 0.4.3 → 0.5.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/README.md +12 -4
- package/package.json +1 -1
- package/src/chat/AgentChatbox.tsx +112 -0
- package/src/chat/AgentPanel.tsx +5 -98
- package/src/chat/chatMessageList.tsx +114 -0
- package/src/chat/common/agentStreamHelpers.ts +104 -0
- package/src/chat/common/createAgentSseSession.ts +304 -0
- package/src/chat/common/types.ts +0 -4
- package/src/chat/common/useAgentChatStream.ts +224 -0
- package/src/chat/common/useAgentStream.ts +28 -367
- package/src/chat/index.ts +5 -1
- package/src/chat/message-ui/ChatInput.tsx +1 -1
- package/src/chat/tool-ui/ChatToolCall.tsx +27 -27
- package/src/dropdown/ContextMenu.tsx +14 -2
- package/src/dropdown/Dropdown.tsx +15 -3
- package/src/dropdown/menuClasses.ts +5 -1
- package/src/index.ts +3 -1
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import type { Dispatch, MutableRefObject, SetStateAction } from "react";
|
|
2
|
+
import {
|
|
3
|
+
failOpenTools,
|
|
4
|
+
finalizeStreaming,
|
|
5
|
+
findToolCallMergeIndex,
|
|
6
|
+
lastToolIndex,
|
|
7
|
+
nextId,
|
|
8
|
+
sameStreamTool,
|
|
9
|
+
thinkingDurationSec,
|
|
10
|
+
} from "./agentStreamHelpers";
|
|
11
|
+
import type { AgentSseCallbacks } from "./sse";
|
|
12
|
+
import type { AgentMessage, AgentToolCallEvent, AgentToolResultEvent } from "./types";
|
|
13
|
+
import { formatToolName, hasMeaningfulInput } from "./utils";
|
|
14
|
+
|
|
15
|
+
export type AgentSseSessionArgs = {
|
|
16
|
+
setMessages: Dispatch<SetStateAction<AgentMessage[]>>;
|
|
17
|
+
setGenerating: (value: boolean) => void;
|
|
18
|
+
thinkingRef: MutableRefObject<string>;
|
|
19
|
+
thinkingStartRef: MutableRefObject<number>;
|
|
20
|
+
openToolsRef: MutableRefObject<Map<string, AgentToolCallEvent>>;
|
|
21
|
+
emitCall: (event: AgentToolCallEvent) => void;
|
|
22
|
+
emitResult: (event: AgentToolResultEvent) => void;
|
|
23
|
+
flushOpenTools: (error: string) => void;
|
|
24
|
+
/** Existing assistant bubble id when resuming mid-stream; omit to start without a bubble. */
|
|
25
|
+
assistantId?: string;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export type AgentSseSession = {
|
|
29
|
+
callbacks: AgentSseCallbacks;
|
|
30
|
+
finishAfterParse: (result: "done" | "error" | "aborted" | "connection-lost") => void;
|
|
31
|
+
finishAbortError: () => void;
|
|
32
|
+
finishThrown: (message: string) => void;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export function createAgentSseSession(args: AgentSseSessionArgs): AgentSseSession {
|
|
36
|
+
const {
|
|
37
|
+
setMessages,
|
|
38
|
+
setGenerating,
|
|
39
|
+
thinkingRef,
|
|
40
|
+
thinkingStartRef,
|
|
41
|
+
openToolsRef,
|
|
42
|
+
emitCall,
|
|
43
|
+
emitResult,
|
|
44
|
+
flushOpenTools,
|
|
45
|
+
assistantId,
|
|
46
|
+
} = args;
|
|
47
|
+
|
|
48
|
+
let assistantText = "";
|
|
49
|
+
let currentId = assistantId ?? "";
|
|
50
|
+
let needsNewBubble = !assistantId;
|
|
51
|
+
|
|
52
|
+
const resetThinking = () => {
|
|
53
|
+
thinkingRef.current = "";
|
|
54
|
+
thinkingStartRef.current = 0;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const freezeOpen = () => {
|
|
58
|
+
const freezeId = currentId;
|
|
59
|
+
if (freezeId) {
|
|
60
|
+
const thinkingSnapshot = thinkingRef.current;
|
|
61
|
+
const liveDuration = thinkingStartRef.current > 0 ? thinkingDurationSec(thinkingStartRef.current) : undefined;
|
|
62
|
+
if (assistantText.trim()) {
|
|
63
|
+
setMessages((prev) =>
|
|
64
|
+
prev.map((m) => {
|
|
65
|
+
if (m.id !== freezeId) return m;
|
|
66
|
+
const existing = typeof m.meta?.thinkingDuration === "number" ? m.meta.thinkingDuration : undefined;
|
|
67
|
+
return {
|
|
68
|
+
...m,
|
|
69
|
+
content: assistantText,
|
|
70
|
+
streaming: false,
|
|
71
|
+
meta: thinkingSnapshot ? { ...m.meta, thinking: thinkingSnapshot, thinkingDuration: liveDuration ?? existing ?? 0 } : m.meta,
|
|
72
|
+
};
|
|
73
|
+
}),
|
|
74
|
+
);
|
|
75
|
+
} else if (thinkingSnapshot) {
|
|
76
|
+
setMessages((prev) =>
|
|
77
|
+
prev.map((m) =>
|
|
78
|
+
m.id === freezeId
|
|
79
|
+
? {
|
|
80
|
+
id: freezeId,
|
|
81
|
+
role: "thinking" as const,
|
|
82
|
+
content: thinkingSnapshot,
|
|
83
|
+
streaming: false,
|
|
84
|
+
timestamp: m.timestamp,
|
|
85
|
+
meta: { thinking: thinkingSnapshot, thinkingDuration: liveDuration ?? 0 },
|
|
86
|
+
}
|
|
87
|
+
: m,
|
|
88
|
+
),
|
|
89
|
+
);
|
|
90
|
+
} else {
|
|
91
|
+
setMessages((prev) => prev.filter((m) => m.id !== freezeId));
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
resetThinking();
|
|
95
|
+
assistantText = "";
|
|
96
|
+
currentId = "";
|
|
97
|
+
needsNewBubble = true;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
const ensureBubble = (seed?: { content?: string; thinking?: string }): string => {
|
|
101
|
+
if (!needsNewBubble && currentId) return currentId;
|
|
102
|
+
const newId = nextId("a");
|
|
103
|
+
currentId = newId;
|
|
104
|
+
needsNewBubble = false;
|
|
105
|
+
setMessages((prev) => [
|
|
106
|
+
...prev,
|
|
107
|
+
{
|
|
108
|
+
id: newId,
|
|
109
|
+
role: "assistant",
|
|
110
|
+
content: seed?.content ?? "",
|
|
111
|
+
streaming: true,
|
|
112
|
+
timestamp: new Date(),
|
|
113
|
+
meta: seed?.thinking ? { thinking: seed.thinking } : undefined,
|
|
114
|
+
},
|
|
115
|
+
]);
|
|
116
|
+
return newId;
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
const stampThinkingDuration = () => {
|
|
120
|
+
if (!thinkingRef.current || !thinkingStartRef.current) return;
|
|
121
|
+
const duration = thinkingDurationSec(thinkingStartRef.current);
|
|
122
|
+
const targetId = currentId;
|
|
123
|
+
if (targetId) {
|
|
124
|
+
setMessages((prev) => prev.map((m) => (m.id === targetId ? { ...m, meta: { ...m.meta, thinkingDuration: duration } } : m)));
|
|
125
|
+
}
|
|
126
|
+
thinkingStartRef.current = 0;
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
const finishTerminalTools = (error: string) => {
|
|
130
|
+
flushOpenTools(error);
|
|
131
|
+
setMessages((prev) => finalizeStreaming(failOpenTools(prev, error)));
|
|
132
|
+
setGenerating(false);
|
|
133
|
+
resetThinking();
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const callbacks: AgentSseCallbacks = {
|
|
137
|
+
onTextDelta: (delta) => {
|
|
138
|
+
stampThinkingDuration();
|
|
139
|
+
if (needsNewBubble || !currentId) {
|
|
140
|
+
assistantText = delta;
|
|
141
|
+
resetThinking();
|
|
142
|
+
ensureBubble({ content: delta });
|
|
143
|
+
} else {
|
|
144
|
+
assistantText += delta;
|
|
145
|
+
const targetId = currentId;
|
|
146
|
+
setMessages((prev) => prev.map((m) => (m.id === targetId ? { ...m, content: assistantText, streaming: true } : m)));
|
|
147
|
+
}
|
|
148
|
+
},
|
|
149
|
+
onThinkingDelta: (delta) => {
|
|
150
|
+
if (needsNewBubble || !currentId) {
|
|
151
|
+
thinkingRef.current = delta;
|
|
152
|
+
thinkingStartRef.current = Date.now();
|
|
153
|
+
assistantText = "";
|
|
154
|
+
ensureBubble({ thinking: delta });
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
if (!thinkingRef.current) thinkingStartRef.current = Date.now();
|
|
158
|
+
thinkingRef.current += delta;
|
|
159
|
+
const thinking = thinkingRef.current;
|
|
160
|
+
const targetId = currentId;
|
|
161
|
+
setMessages((prev) => prev.map((m) => (m.id === targetId ? { ...m, meta: { ...m.meta, thinking } } : m)));
|
|
162
|
+
},
|
|
163
|
+
onToolCall: (event) => {
|
|
164
|
+
const label = event.toolLabel ? (event.toolLabel.includes(" ") ? event.toolLabel : formatToolName(event.toolLabel)) : formatToolName(event.toolName);
|
|
165
|
+
|
|
166
|
+
const call: AgentToolCallEvent = {
|
|
167
|
+
toolCallId: event.toolCallId,
|
|
168
|
+
toolName: event.toolName,
|
|
169
|
+
toolLabel: label,
|
|
170
|
+
input: event.input,
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
freezeOpen();
|
|
174
|
+
setMessages((prev) => {
|
|
175
|
+
const idx = findToolCallMergeIndex(prev, { ...event, toolLabel: label });
|
|
176
|
+
if (idx !== -1) {
|
|
177
|
+
const target = prev[idx];
|
|
178
|
+
const nextInput = hasMeaningfulInput(event.input) ? event.input : target.toolInput;
|
|
179
|
+
const mergedCallId = event.toolCallId ?? target.toolCallId;
|
|
180
|
+
if (target.toolOutput == null) {
|
|
181
|
+
const mapKey =
|
|
182
|
+
[...openToolsRef.current.entries()].find(([, t]) => t.toolCallId === target.toolCallId || t.toolName === target.toolName)?.[0] ??
|
|
183
|
+
mergedCallId ??
|
|
184
|
+
target.id;
|
|
185
|
+
openToolsRef.current.set(mapKey, { ...call, toolCallId: mergedCallId, input: nextInput });
|
|
186
|
+
}
|
|
187
|
+
return prev.map((m, i) =>
|
|
188
|
+
i === idx
|
|
189
|
+
? {
|
|
190
|
+
...m,
|
|
191
|
+
content: event.toolName,
|
|
192
|
+
toolCallId: mergedCallId,
|
|
193
|
+
toolName: event.toolName,
|
|
194
|
+
toolLabel: label,
|
|
195
|
+
toolInput: nextInput,
|
|
196
|
+
}
|
|
197
|
+
: m,
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const id = nextId("tc");
|
|
202
|
+
openToolsRef.current.set(event.toolCallId || id, call);
|
|
203
|
+
return [
|
|
204
|
+
...prev,
|
|
205
|
+
{
|
|
206
|
+
id,
|
|
207
|
+
role: "tool-call" as const,
|
|
208
|
+
content: event.toolName,
|
|
209
|
+
toolCallId: event.toolCallId,
|
|
210
|
+
toolName: event.toolName,
|
|
211
|
+
toolLabel: label,
|
|
212
|
+
toolInput: event.input,
|
|
213
|
+
timestamp: new Date(),
|
|
214
|
+
},
|
|
215
|
+
];
|
|
216
|
+
});
|
|
217
|
+
if (event.input !== undefined) emitCall(call);
|
|
218
|
+
},
|
|
219
|
+
onToolResult: (event) => {
|
|
220
|
+
const raw = event.result;
|
|
221
|
+
const resultStr = typeof raw === "string" ? raw : JSON.stringify(raw);
|
|
222
|
+
const resultLabel = formatToolName(event.toolName);
|
|
223
|
+
if (event.toolCallId) {
|
|
224
|
+
openToolsRef.current.delete(event.toolCallId);
|
|
225
|
+
} else {
|
|
226
|
+
for (const [key, tool] of [...openToolsRef.current.entries()].reverse()) {
|
|
227
|
+
if (tool.toolName === event.toolName) {
|
|
228
|
+
openToolsRef.current.delete(key);
|
|
229
|
+
break;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
freezeOpen();
|
|
234
|
+
setMessages((prev) => {
|
|
235
|
+
let matchIdx = -1;
|
|
236
|
+
if (event.toolCallId) {
|
|
237
|
+
matchIdx = prev.findIndex((m) => m.role === "tool-call" && m.toolCallId === event.toolCallId);
|
|
238
|
+
}
|
|
239
|
+
if (matchIdx === -1) {
|
|
240
|
+
matchIdx = lastToolIndex(prev, (m) => sameStreamTool(m, event.toolName, resultLabel) && m.toolOutput == null);
|
|
241
|
+
}
|
|
242
|
+
if (matchIdx !== -1) {
|
|
243
|
+
return prev.map((m, i) => (i === matchIdx ? { ...m, toolOutput: resultStr, toolCallId: event.toolCallId ?? m.toolCallId } : m));
|
|
244
|
+
}
|
|
245
|
+
const id = nextId("tc");
|
|
246
|
+
return [
|
|
247
|
+
...prev,
|
|
248
|
+
{
|
|
249
|
+
id,
|
|
250
|
+
role: "tool-call" as const,
|
|
251
|
+
content: event.toolName,
|
|
252
|
+
toolCallId: event.toolCallId,
|
|
253
|
+
toolName: event.toolName,
|
|
254
|
+
toolLabel: resultLabel,
|
|
255
|
+
toolOutput: resultStr,
|
|
256
|
+
timestamp: new Date(),
|
|
257
|
+
},
|
|
258
|
+
];
|
|
259
|
+
});
|
|
260
|
+
emitResult({ toolCallId: event.toolCallId, toolName: event.toolName, output: raw });
|
|
261
|
+
},
|
|
262
|
+
onDone: () => {
|
|
263
|
+
finishTerminalTools("Tool did not return a result");
|
|
264
|
+
},
|
|
265
|
+
onError: (error) => {
|
|
266
|
+
const reason = error === "cancelled" ? "Cancelled" : error;
|
|
267
|
+
flushOpenTools(reason);
|
|
268
|
+
if (error === "Connection lost") {
|
|
269
|
+
setMessages((prev) => finalizeStreaming(failOpenTools(prev, "Connection lost")));
|
|
270
|
+
setGenerating(false);
|
|
271
|
+
resetThinking();
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
setMessages((prev) => [
|
|
275
|
+
...finalizeStreaming(failOpenTools(prev, reason)),
|
|
276
|
+
...(error === "cancelled" ? [] : [{ id: nextId("err"), role: "error" as const, content: error, timestamp: new Date() }]),
|
|
277
|
+
]);
|
|
278
|
+
setGenerating(false);
|
|
279
|
+
resetThinking();
|
|
280
|
+
},
|
|
281
|
+
};
|
|
282
|
+
|
|
283
|
+
return {
|
|
284
|
+
callbacks,
|
|
285
|
+
finishAfterParse: (result) => {
|
|
286
|
+
if (result === "aborted") {
|
|
287
|
+
finishTerminalTools("Cancelled");
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
// Match AgentPanel stream: always finalize open tools after parse returns.
|
|
291
|
+
finishTerminalTools("Tool did not return a result");
|
|
292
|
+
},
|
|
293
|
+
finishAbortError: () => finishTerminalTools("Cancelled"),
|
|
294
|
+
finishThrown: (message) => {
|
|
295
|
+
flushOpenTools(message);
|
|
296
|
+
setMessages((prev) => [
|
|
297
|
+
...finalizeStreaming(failOpenTools(prev, message)),
|
|
298
|
+
{ id: nextId("err"), role: "error", content: message, timestamp: new Date() },
|
|
299
|
+
]);
|
|
300
|
+
setGenerating(false);
|
|
301
|
+
resetThinking();
|
|
302
|
+
},
|
|
303
|
+
};
|
|
304
|
+
}
|
package/src/chat/common/types.ts
CHANGED
|
@@ -62,7 +62,3 @@ export type AgentToolHook = {
|
|
|
62
62
|
onCall?: (event: AgentToolCallEvent) => void;
|
|
63
63
|
onResult?: (event: AgentToolResultEvent) => void;
|
|
64
64
|
};
|
|
65
|
-
|
|
66
|
-
export type AgentToolAction =
|
|
67
|
-
| ({ type: "tool-call" } & AgentToolCallEvent)
|
|
68
|
-
| ({ type: "tool-result" } & AgentToolResultEvent);
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
2
|
+
import { failOpenTools, finalizeStreaming, nextId } from "./agentStreamHelpers";
|
|
3
|
+
import { createAgentSseSession } from "./createAgentSseSession";
|
|
4
|
+
import { parseSseStream } from "./sse";
|
|
5
|
+
import type { AgentMessage, AgentToolCallEvent, AgentToolHook, AgentToolResultEvent } from "./types";
|
|
6
|
+
import { matchesToolHook } from "./utils";
|
|
7
|
+
|
|
8
|
+
export type AgentChatSendRequest = { text: string; signal: AbortSignal };
|
|
9
|
+
export type AgentChatResumeRequest = { signal: AbortSignal };
|
|
10
|
+
|
|
11
|
+
export type UseAgentChatStreamOptions = {
|
|
12
|
+
/** Seed display messages (mount only — remount to change conversation). */
|
|
13
|
+
initialMessages?: AgentMessage[];
|
|
14
|
+
/** App POSTs only the new message; returns an SSE `Response`. */
|
|
15
|
+
send: (req: AgentChatSendRequest) => Promise<Response>;
|
|
16
|
+
/** On mount: reattach a live stream. `null` / no body = idle. */
|
|
17
|
+
resume?: (req: AgentChatResumeRequest) => Promise<Response | null>;
|
|
18
|
+
/** User hit Stop — abort client then notify app to cancel server generation. */
|
|
19
|
+
onStop?: () => void | Promise<void>;
|
|
20
|
+
toolHooks?: AgentToolHook[];
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
type OpenTool = AgentToolCallEvent;
|
|
24
|
+
|
|
25
|
+
export function useAgentChatStream({ initialMessages, send: sendRequest, resume, onStop, toolHooks }: UseAgentChatStreamOptions) {
|
|
26
|
+
const [messages, setMessages] = useState<AgentMessage[]>(() => initialMessages ?? []);
|
|
27
|
+
const messagesRef = useRef(messages);
|
|
28
|
+
messagesRef.current = messages;
|
|
29
|
+
const [generating, setGenerating] = useState(false);
|
|
30
|
+
const thinkingRef = useRef("");
|
|
31
|
+
const thinkingStartRef = useRef(0);
|
|
32
|
+
const abortRef = useRef<AbortController | null>(null);
|
|
33
|
+
const toolHooksRef = useRef(toolHooks);
|
|
34
|
+
toolHooksRef.current = toolHooks;
|
|
35
|
+
const sendRef = useRef(sendRequest);
|
|
36
|
+
sendRef.current = sendRequest;
|
|
37
|
+
const resumeRef = useRef(resume);
|
|
38
|
+
resumeRef.current = resume;
|
|
39
|
+
const onStopRef = useRef(onStop);
|
|
40
|
+
onStopRef.current = onStop;
|
|
41
|
+
const openToolsRef = useRef<Map<string, OpenTool>>(new Map());
|
|
42
|
+
const resumedRef = useRef(false);
|
|
43
|
+
|
|
44
|
+
const emitCall = useCallback((event: AgentToolCallEvent) => {
|
|
45
|
+
for (const hook of toolHooksRef.current ?? []) {
|
|
46
|
+
if (matchesToolHook(hook.name, event.toolName)) hook.onCall?.(event);
|
|
47
|
+
}
|
|
48
|
+
}, []);
|
|
49
|
+
|
|
50
|
+
const emitResult = useCallback((event: AgentToolResultEvent) => {
|
|
51
|
+
for (const hook of toolHooksRef.current ?? []) {
|
|
52
|
+
if (matchesToolHook(hook.name, event.toolName)) hook.onResult?.(event);
|
|
53
|
+
}
|
|
54
|
+
}, []);
|
|
55
|
+
|
|
56
|
+
const flushOpenTools = useCallback(
|
|
57
|
+
(error: string) => {
|
|
58
|
+
const open = [...openToolsRef.current.values()];
|
|
59
|
+
if (!open.length) return;
|
|
60
|
+
openToolsRef.current.clear();
|
|
61
|
+
for (const tool of open) {
|
|
62
|
+
emitResult({
|
|
63
|
+
toolCallId: tool.toolCallId,
|
|
64
|
+
toolName: tool.toolName,
|
|
65
|
+
output: { success: false, error },
|
|
66
|
+
error,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
[emitResult],
|
|
71
|
+
);
|
|
72
|
+
|
|
73
|
+
const cancel = useCallback(() => {
|
|
74
|
+
abortRef.current?.abort();
|
|
75
|
+
abortRef.current = null;
|
|
76
|
+
flushOpenTools("Cancelled");
|
|
77
|
+
setMessages((prev) => finalizeStreaming(failOpenTools(prev, "Cancelled")));
|
|
78
|
+
setGenerating(false);
|
|
79
|
+
thinkingRef.current = "";
|
|
80
|
+
thinkingStartRef.current = 0;
|
|
81
|
+
void onStopRef.current?.();
|
|
82
|
+
}, [flushOpenTools]);
|
|
83
|
+
|
|
84
|
+
useEffect(() => {
|
|
85
|
+
return () => {
|
|
86
|
+
abortRef.current?.abort();
|
|
87
|
+
abortRef.current = null;
|
|
88
|
+
};
|
|
89
|
+
}, []);
|
|
90
|
+
|
|
91
|
+
const attachStream = useCallback(
|
|
92
|
+
async (response: Response, opts?: { assistantId?: string }) => {
|
|
93
|
+
if (!response.ok || !response.body) {
|
|
94
|
+
const errText = await response.text().catch(() => "");
|
|
95
|
+
throw new Error(errText || `HTTP ${response.status}`);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const session = createAgentSseSession({
|
|
99
|
+
setMessages,
|
|
100
|
+
setGenerating,
|
|
101
|
+
thinkingRef,
|
|
102
|
+
thinkingStartRef,
|
|
103
|
+
openToolsRef,
|
|
104
|
+
emitCall,
|
|
105
|
+
emitResult,
|
|
106
|
+
flushOpenTools,
|
|
107
|
+
assistantId: opts?.assistantId,
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
try {
|
|
111
|
+
const result = await parseSseStream(response.body, session.callbacks, {
|
|
112
|
+
signal: abortRef.current?.signal,
|
|
113
|
+
});
|
|
114
|
+
session.finishAfterParse(result);
|
|
115
|
+
} catch (err: unknown) {
|
|
116
|
+
if ((err as Error)?.name === "AbortError") {
|
|
117
|
+
session.finishAbortError();
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
session.finishThrown(err instanceof Error ? err.message : String(err));
|
|
121
|
+
} finally {
|
|
122
|
+
abortRef.current = null;
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
[emitCall, emitResult, flushOpenTools],
|
|
126
|
+
);
|
|
127
|
+
|
|
128
|
+
// Resume live stream once on mount.
|
|
129
|
+
useEffect(() => {
|
|
130
|
+
if (resumedRef.current) return;
|
|
131
|
+
resumedRef.current = true;
|
|
132
|
+
const resumeFn = resumeRef.current;
|
|
133
|
+
if (!resumeFn) return;
|
|
134
|
+
|
|
135
|
+
let cancelled = false;
|
|
136
|
+
const controller = new AbortController();
|
|
137
|
+
abortRef.current = controller;
|
|
138
|
+
|
|
139
|
+
void (async () => {
|
|
140
|
+
try {
|
|
141
|
+
const response = await resumeFn({ signal: controller.signal });
|
|
142
|
+
if (cancelled || !response || !response.body) {
|
|
143
|
+
abortRef.current = null;
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
setGenerating(true);
|
|
147
|
+
thinkingRef.current = "";
|
|
148
|
+
thinkingStartRef.current = 0;
|
|
149
|
+
|
|
150
|
+
// Continue the last streaming assistant bubble when history left one open.
|
|
151
|
+
const last = messagesRef.current[messagesRef.current.length - 1];
|
|
152
|
+
const assistantId = last?.role === "assistant" && last.streaming ? last.id : undefined;
|
|
153
|
+
await attachStream(response, { assistantId });
|
|
154
|
+
} catch (err: unknown) {
|
|
155
|
+
if ((err as Error)?.name === "AbortError" || cancelled) return;
|
|
156
|
+
setMessages((prev) => [
|
|
157
|
+
...finalizeStreaming(failOpenTools(prev, err instanceof Error ? err.message : String(err))),
|
|
158
|
+
{
|
|
159
|
+
id: nextId("err"),
|
|
160
|
+
role: "error",
|
|
161
|
+
content: err instanceof Error ? err.message : String(err),
|
|
162
|
+
timestamp: new Date(),
|
|
163
|
+
},
|
|
164
|
+
]);
|
|
165
|
+
setGenerating(false);
|
|
166
|
+
abortRef.current = null;
|
|
167
|
+
}
|
|
168
|
+
})();
|
|
169
|
+
|
|
170
|
+
return () => {
|
|
171
|
+
cancelled = true;
|
|
172
|
+
controller.abort();
|
|
173
|
+
};
|
|
174
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps -- mount-only resume
|
|
175
|
+
}, [attachStream]);
|
|
176
|
+
|
|
177
|
+
const send = useCallback(
|
|
178
|
+
async (text: string) => {
|
|
179
|
+
const trimmed = text.trim();
|
|
180
|
+
if (!trimmed || generating) return;
|
|
181
|
+
|
|
182
|
+
abortRef.current?.abort();
|
|
183
|
+
flushOpenTools("Cancelled");
|
|
184
|
+
const controller = new AbortController();
|
|
185
|
+
abortRef.current = controller;
|
|
186
|
+
|
|
187
|
+
const userMsg: AgentMessage = { id: nextId("u"), role: "user", content: trimmed, timestamp: new Date() };
|
|
188
|
+
const assistantId = nextId("a");
|
|
189
|
+
const assistantMsg: AgentMessage = { id: assistantId, role: "assistant", content: "", streaming: true, timestamp: new Date() };
|
|
190
|
+
|
|
191
|
+
setMessages((prev) => [...prev, userMsg, assistantMsg]);
|
|
192
|
+
setGenerating(true);
|
|
193
|
+
thinkingRef.current = "";
|
|
194
|
+
thinkingStartRef.current = 0;
|
|
195
|
+
|
|
196
|
+
try {
|
|
197
|
+
const response = await sendRef.current({ text: trimmed, signal: controller.signal });
|
|
198
|
+
await attachStream(response, { assistantId });
|
|
199
|
+
} catch (err: unknown) {
|
|
200
|
+
if ((err as Error)?.name === "AbortError") {
|
|
201
|
+
flushOpenTools("Cancelled");
|
|
202
|
+
setMessages((prev) => finalizeStreaming(failOpenTools(prev, "Cancelled")));
|
|
203
|
+
setGenerating(false);
|
|
204
|
+
thinkingRef.current = "";
|
|
205
|
+
thinkingStartRef.current = 0;
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
209
|
+
flushOpenTools(message);
|
|
210
|
+
setMessages((prev) => [
|
|
211
|
+
...finalizeStreaming(failOpenTools(prev, message)),
|
|
212
|
+
{ id: nextId("err"), role: "error", content: message, timestamp: new Date() },
|
|
213
|
+
]);
|
|
214
|
+
setGenerating(false);
|
|
215
|
+
thinkingRef.current = "";
|
|
216
|
+
thinkingStartRef.current = 0;
|
|
217
|
+
abortRef.current = null;
|
|
218
|
+
}
|
|
219
|
+
},
|
|
220
|
+
[generating, flushOpenTools, attachStream],
|
|
221
|
+
);
|
|
222
|
+
|
|
223
|
+
return { messages, generating, send, cancel };
|
|
224
|
+
}
|