-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathcommon-agent-area.tsx
More file actions
284 lines (250 loc) · 8.3 KB
/
common-agent-area.tsx
File metadata and controls
284 lines (250 loc) · 8.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import { useQueryClient } from "@tanstack/react-query";
import { type FC, memo, useCallback, useEffect, useState } from "react";
import {
Navigate,
useLocation,
useNavigate,
useSearchParams,
} from "react-router";
import { toast } from "sonner";
import { useGetAgentInfo } from "@/api/agent";
import { useGetConversationHistory, usePollTaskList } from "@/api/conversation";
import { API_QUERY_KEYS } from "@/constants/api";
import useSSE from "@/hooks/use-sse";
import { getServerUrl } from "@/lib/api-client";
import { tracker } from "@/lib/tracker";
import {
MultiSectionProvider,
useMultiSection,
} from "@/provider/multi-section-provider";
import {
useAgentStoreActions,
useCurrentConversation,
} from "@/store/agent-store";
import type {
AgentStreamRequest,
AgentViewProps,
MultiSectionComponentType,
SectionComponentType,
SSEData,
} from "@/types/agent";
import {
ChatConversationHeader,
ChatInputArea,
ChatMultiSectionComponent,
ChatSectionComponent,
ChatThreadArea,
ChatWelcomeScreen,
} from "../chat-conversation";
interface CommonAgentAreaProps {
agentName: string;
}
const CommonAgentAreaContent: FC<CommonAgentAreaProps> = ({ agentName }) => {
const { data: agent, isLoading: isLoadingAgent } = useGetAgentInfo({
agentName: agentName ?? "",
});
const conversationId = useSearchParams()[0].get("id") ?? "";
const navigate = useNavigate();
const inputValueFromLocation = useLocation().state?.inputValue;
// Use optimized hooks with built-in shallow comparison
const { curConversation, curConversationId } = useCurrentConversation();
const {
dispatchAgentStore,
setCurConversationId,
dispatchAgentStoreHistory,
} = useAgentStoreActions();
const queryClient = useQueryClient();
const { data: conversationHistory } =
useGetConversationHistory(conversationId);
const { data: taskList } = usePollTaskList(conversationId);
// Load conversation history (only once when conversation changes)
useEffect(() => {
if (
!conversationId ||
!conversationHistory ||
conversationHistory.length === 0
)
return;
dispatchAgentStoreHistory(conversationId, conversationHistory, true);
}, [conversationId, conversationHistory, dispatchAgentStoreHistory]);
// Update task list (polls every 30s)
useEffect(() => {
if (!conversationId || !taskList || taskList.length === 0) return;
dispatchAgentStoreHistory(conversationId, taskList);
}, [conversationId, taskList, dispatchAgentStoreHistory]);
// Initialize SSE connection using the useSSE hook
const { connect, close, isStreaming } = useSSE({
url: getServerUrl("/agents/stream"),
handlers: {
onData: (sseData: SSEData) => {
// Update agent store using the reducer
dispatchAgentStore(sseData);
// Handle specific UI state updates
const { event, data } = sseData;
switch (event) {
case "conversation_started":
navigate(`/agent/${agentName}?id=${data.conversation_id}`, {
replace: true,
});
queryClient.invalidateQueries({
queryKey: API_QUERY_KEYS.CONVERSATION.conversationList,
});
break;
case "component_generator":
if (data.payload.component_type === "subagent_conversation") {
queryClient.invalidateQueries({
queryKey: API_QUERY_KEYS.CONVERSATION.conversationList,
});
}
break;
case "system_failed":
// Handle system errors in UI layer
toast.error(data.payload.content, {
closeButton: true,
duration: 30 * 1000,
});
break;
case "done":
close();
break;
// All message-related events are handled by the store
default:
break;
}
},
onOpen: () => {
console.log("✅ SSE connection opened");
},
onError: (error: Error) => {
console.error("❌ SSE connection error:", error);
},
onClose: () => {
console.log("🔌 SSE connection closed");
},
},
});
// Send message to agent
// biome-ignore lint/correctness/useExhaustiveDependencies: connect is no need to be in dependencies
const sendMessage = useCallback(
async (message: string) => {
try {
const request: AgentStreamRequest = {
query: message,
agent_name: agentName,
conversation_id: conversationId,
};
tracker.send("use", {
agent_name: agentName,
});
// Connect SSE client with request body to receive streaming response
await connect(JSON.stringify(request));
} catch (error) {
console.error("Failed to send message:", error);
}
},
[agentName, conversationId],
);
useEffect(() => {
if (curConversationId !== conversationId) {
setCurConversationId(conversationId);
}
}, [setCurConversationId, curConversationId, conversationId]);
useEffect(() => {
if (inputValueFromLocation) {
sendMessage(inputValueFromLocation);
// Clear the state after using it once to prevent re-triggering on page refresh
navigate(".", { replace: true, state: {} });
}
}, [inputValueFromLocation, navigate, sendMessage]);
const [inputValue, setInputValue] = useState<string>("");
const { currentSection } = useMultiSection();
const handleSendMessage = useCallback(async () => {
if (!inputValue.trim()) return;
try {
await sendMessage(inputValue);
setInputValue("");
} catch (error) {
// Keep input value on error so user doesn't lose their text
console.error("Failed to send message:", error);
}
}, [inputValue, sendMessage]);
const handleInputChange = useCallback((value: string) => {
setInputValue(value);
}, []);
if (isLoadingAgent) return null;
if (!agent) return <Navigate to="/" replace />;
// Check if conversation has any messages
const hasMessages =
curConversation?.threads && Object.keys(curConversation.threads).length > 0;
if (!hasMessages) {
return (
<>
<ChatConversationHeader agent={agent} />
<ChatWelcomeScreen
title={`Welcome to ${agent.display_name}!`}
inputValue={inputValue}
onInputChange={handleInputChange}
onSendMessage={handleSendMessage}
disabled={isStreaming}
/>
</>
);
}
return (
<div className="flex flex-1 overflow-hidden">
{/* main section */}
<section className="flex flex-1 flex-col items-center">
<ChatConversationHeader agent={agent} />
<ChatThreadArea
threads={curConversation.threads}
isStreaming={isStreaming}
/>
{/* Input area now only in main section */}
<ChatInputArea
className="main-chat-area mb-8"
value={inputValue}
onChange={handleInputChange}
onSend={handleSendMessage}
placeholder="Type your message..."
disabled={isStreaming}
variant="chat"
/>
</section>
{/* Chat section components: one section per special component_type */}
{Object.entries(curConversation.sections).map(
([componentType, threadView]) => {
return (
<ChatSectionComponent
key={componentType}
// TODO: componentType as type assertion is not safe, find a better way to do this
componentType={componentType as SectionComponentType}
threadView={threadView}
/>
);
},
)}
{/* Multi-section detail view */}
{currentSection && (
<section className="flex flex-1 flex-col py-4">
<div className="scroll-container">
<ChatMultiSectionComponent
componentType={
// only the component_type is the same as the MultiSectionComponentType
currentSection.component_type as MultiSectionComponentType
}
content={currentSection.payload.content}
/>
</div>
</section>
)}
</div>
);
};
const CommonAgentArea: FC<AgentViewProps> = (props) => {
return (
<MultiSectionProvider>
<CommonAgentAreaContent {...props} />
</MultiSectionProvider>
);
};
export default memo(CommonAgentArea);