-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathExistingChat.jsx
More file actions
531 lines (486 loc) · 16.7 KB
/
ExistingChat.jsx
File metadata and controls
531 lines (486 loc) · 16.7 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
import { memo, useEffect, useRef, useState, useMemo, useCallback } from "react";
import PropTypes from "prop-types";
import { Space, Button, Typography, Input, Spin } from "antd";
import {
ArrowDownOutlined,
EditOutlined,
CheckOutlined,
CloseOutlined,
} from "@ant-design/icons";
import { useChatAIService } from "./services";
import { InputPrompt } from "./InputPrompt";
import { Conversation } from "./Conversation";
import { LowBalanceWarning } from "./LowBalanceWarning";
import { TodoGuide } from "./TodoGuide";
import { OnboardingGuide } from "./OnboardingGuide";
import { OnboardingCompletionPopup } from "./OnboardingCompletionPopup";
import { useNotificationService } from "../../service/notification-service";
import { useAxiosPrivate } from "../../service/axios-service";
import { SpinnerLoader } from "../../widgets/spinner_loader";
import { useSessionStore } from "../../store/session-store";
// Cloud-only: fetch per-message token usage (unavailable in OSS — import fails gracefully)
let getTokenUsage = null;
try {
({ getTokenUsage } = require("../../plugins/token-management/token-usage"));
} catch {
// OSS: token usage API not available
}
const ExistingChat = memo(function ExistingChat({
selectedChatId,
chatName,
setChatName,
savePrompt,
chatMessages,
setChatMessages,
isGetChatMessages,
resetChatMessageIdentifier,
isPromptRunning,
chatIntents,
selectedChatIntent,
setSelectedChatIntent,
llmModels,
selectedLlmModel,
setSelectedLlmModel,
selectedCoderLlmModel,
setSelectedCoderLlmModel,
handleTransformApply,
triggerRetryTransform,
stopPromptRun,
handleSqlRun,
promptAutoComplete,
isChatConversationDisabled,
tokenUsageData,
isTodoGuideVisible,
onPromptSelect,
selectedPrompt,
completedTodoTasks,
onCompletedTodoTasksChange,
// Onboarding props
isOnboardingMode,
onboardingConfig,
completedOnboardingSteps,
skippedOnboardingSteps,
currentOnboardingStep,
isTypingPrompt,
onOnboardingPromptSelect,
onSkipOnboarding,
onOnboardingComplete,
onSkipCurrentTask,
onSendButtonClick,
}) {
const { getChatMessagesByChatId, updateChatName } = useChatAIService();
const axiosPrivate = useAxiosPrivate();
const isCloud = useSessionStore((state) => state.sessionDetails?.is_cloud);
const chatContainerRef = useRef(null);
const [isLoadingChats, setIsLoadingChats] = useState(false);
const [lastChatMessageId, setLastChatMessageId] = useState(null);
const [isAtBottom, setIsAtBottom] = useState(true);
const [showCompletionPopup, setShowCompletionPopup] = useState(false);
const [hasShownCompletion, setHasShownCompletion] = useState(false);
// Title bar inline edit state
const [isEditingTitle, setIsEditingTitle] = useState(false);
const [editTitleValue, setEditTitleValue] = useState("");
const [isSavingTitle, setIsSavingTitle] = useState(false);
const { notify } = useNotificationService();
const ellipsisConfig = useMemo(() => ({ tooltip: chatName }), [chatName]);
// Check if onboarding is complete (progress 100%)
useEffect(() => {
// Don't check if no config
if (!onboardingConfig) {
return;
}
// Check multiple conditions for completion
const isComplete =
onboardingConfig?.progress?.progress_percentage === 100 ||
(onboardingConfig?.progress?.completed_tasks ===
onboardingConfig?.progress?.total_tasks &&
onboardingConfig?.progress?.total_tasks > 0);
// Show popup if tasks are 100% complete AND not already marked as completed in database
// Don't require isOnboardingMode because tasks might complete while in existing chat
if (
onboardingConfig &&
isComplete &&
!onboardingConfig.is_completed &&
!showCompletionPopup &&
!hasShownCompletion
) {
setShowCompletionPopup(true);
} else if (onboardingConfig?.is_completed) {
// Make sure popup is hidden if already completed
if (showCompletionPopup) {
setShowCompletionPopup(false);
}
// Reset the flag for future use
if (hasShownCompletion) {
setHasShownCompletion(false);
}
}
}, [onboardingConfig, showCompletionPopup, isOnboardingMode, hasShownCompletion]);
// Handle prompt selection from TodoGuide
const handlePromptSelect = useCallback(
(prompt) => {
if (onPromptSelect) {
onPromptSelect(prompt);
}
},
[onPromptSelect]
);
// Title bar handlers
const handleStartEditTitle = useCallback(() => {
setIsEditingTitle(true);
setEditTitleValue(chatName || "");
}, [chatName]);
const handleCancelEditTitle = useCallback(() => {
setIsEditingTitle(false);
setEditTitleValue("");
}, []);
const handleSaveTitle = useCallback(async () => {
const trimmed = editTitleValue.trim();
if (!trimmed || trimmed === chatName) {
setIsEditingTitle(false);
return;
}
setIsSavingTitle(true);
try {
await updateChatName(selectedChatId, trimmed);
setChatName(trimmed);
setIsEditingTitle(false);
setEditTitleValue("");
} catch (error) {
console.error("Failed to update chat name:", error);
notify({ error });
} finally {
setIsSavingTitle(false);
}
}, [
editTitleValue,
chatName,
selectedChatId,
updateChatName,
setChatName,
notify,
]);
const handleTitleKeyDown = useCallback(
(e) => {
if (e.key === "Enter") {
handleSaveTitle();
} else if (e.key === "Escape") {
handleCancelEditTitle();
}
},
[handleSaveTitle, handleCancelEditTitle]
);
// Handle completion popup close
const handleCompletionPopupClose = useCallback(() => {
setShowCompletionPopup(false);
}, []);
// Handle completion popup continue
const handleCompletionPopupContinue = useCallback(() => {
// Immediately close popup to prevent flickering
setShowCompletionPopup(false);
// Set a flag to prevent popup from showing again during API call
setHasShownCompletion(true);
// Call the onOnboardingComplete handler if available
if (onOnboardingComplete) {
onOnboardingComplete();
} else {
// Fallback to skip if no complete handler
if (onSkipOnboarding) {
onSkipOnboarding();
}
}
}, [onOnboardingComplete, onSkipOnboarding]);
// Use original savePrompt directly since selectedPrompt is now managed by parent
const handleSavePrompt = useCallback(
(...args) => {
savePrompt(...args); // Call the original savePrompt
},
[savePrompt]
);
// runs on every scroll via onScroll
const handleScroll = useCallback(() => {
if (!chatContainerRef.current) return;
const { scrollTop, scrollHeight, clientHeight } = chatContainerRef.current;
const nearBottom = scrollHeight - (scrollTop + clientHeight) < 50;
setIsAtBottom(nearBottom);
}, []);
const scrollToBottom = () => {
if (chatContainerRef.current) {
chatContainerRef.current.scrollTop =
chatContainerRef.current.scrollHeight;
setIsAtBottom(true);
}
};
const lastTransformIndex = useMemo(() => {
const intentsMap = chatIntents.reduce((acc, ci) => {
acc[ci?.chat_intent_id] = ci?.name;
return acc;
}, {});
for (let i = chatMessages.length - 1; i >= 0; i--) {
if (intentsMap[chatMessages[i]?.chat_intent] === "TRANSFORM") return i;
}
return -1;
}, [chatMessages, chatIntents]);
useEffect(() => {
if (chatMessages.length) {
setLastChatMessageId(
chatMessages[chatMessages.length - 1]?.chat_message_id
);
}
}, [chatMessages]);
// cleanup on unmount
useEffect(() => () => setChatMessages([]), [setChatMessages]);
// fetch messages on chat change / refresh
useEffect(() => {
if (isGetChatMessages && selectedChatId) fetchChatMessages();
}, [isGetChatMessages, selectedChatId]);
const fetchChatMessages = async () => {
try {
setIsLoadingChats(true);
const apiData = await getChatMessagesByChatId(selectedChatId);
const updatedData = (apiData || []).map((msg) => ({
...msg,
response: Array.isArray(msg.response)
? msg.response
: [msg.response].filter(Boolean),
}));
// Fetch token usage for all messages to display in historical conversations.
// Only available in cloud mode via the token-usage plugin.
if (getTokenUsage && isCloud && updatedData.length > 0) {
const tokenUsagePromises = updatedData.map((msg) =>
getTokenUsage(
axiosPrivate,
selectedChatId,
msg.chat_message_id
).catch(() => null)
);
const tokenUsageResults = await Promise.all(tokenUsagePromises);
tokenUsageResults.forEach((tokenUsage, index) => {
if (tokenUsage) {
updatedData[index] = {
...updatedData[index],
token_usage_data: tokenUsage,
};
}
});
}
setChatMessages(updatedData);
setIsAtBottom(true);
} catch (error) {
console.error(error);
notify({ error });
} finally {
setIsLoadingChats(false);
resetChatMessageIdentifier();
}
};
// auto-scroll when new messages arrive, but only if user is already at bottom
useEffect(() => {
if (isAtBottom) scrollToBottom();
}, [chatMessages]);
if (!selectedChatId) return null;
if (isLoadingChats) {
return <SpinnerLoader />;
}
// Position button relative to container - always above the prompt area
const scrollToBottomStyle = {
position: "absolute",
bottom: 180,
right: 24,
zIndex: 100,
boxShadow: "0 2px 8px rgba(0,0,0,0.15)",
};
return (
<div className="existing-chat-outer-container">
{chatName && (
<div className="chat-title-bar">
{isEditingTitle ? (
<div className="chat-title-edit-row">
<Input
value={editTitleValue}
onChange={(e) => setEditTitleValue(e.target.value)}
onKeyDown={handleTitleKeyDown}
onClick={(e) => e.stopPropagation()}
className="chat-title-edit-input"
autoFocus
maxLength={100}
size="small"
/>
<Space size={4}>
{isSavingTitle ? (
<Spin size="small" />
) : (
<CheckOutlined
onClick={handleSaveTitle}
className="chat-title-action-icon"
/>
)}
<CloseOutlined
onClick={isSavingTitle ? undefined : handleCancelEditTitle}
className="chat-title-action-icon"
style={
isSavingTitle
? { pointerEvents: "none", opacity: 0.5 }
: undefined
}
/>
</Space>
</div>
) : (
<div className="chat-title-display-row">
<Typography.Text
ellipsis={ellipsisConfig}
className="chat-title-text"
>
{chatName}
</Typography.Text>
<EditOutlined
onClick={handleStartEditTitle}
className="chat-title-edit-icon"
/>
</div>
)}
</div>
)}
<div
ref={chatContainerRef}
className="chat-ai-existing-chat-container"
onScroll={handleScroll}
>
<Space direction="vertical" className="width-100">
{chatMessages.map((message, idx) => (
<Conversation
key={message.chat_message_id}
message={message}
chatIntents={chatIntents}
llmModels={llmModels}
isPromptRunning={isPromptRunning}
isLastConversation={idx === chatMessages.length - 1}
selectedChatId={selectedChatId}
handleTransformApply={handleTransformApply}
triggerRetryTransform={triggerRetryTransform}
handleSqlRun={handleSqlRun}
isLatestTransform={idx === lastTransformIndex}
savePrompt={handleSavePrompt}
selectedChatIntent={selectedChatIntent}
/>
))}
</Space>
</div>
{!isAtBottom && (
<Button
shape="round"
onClick={scrollToBottom}
icon={<ArrowDownOutlined />}
style={scrollToBottomStyle}
/>
)}
<div className="pad-8">
<LowBalanceWarning tokenUsageData={tokenUsageData} />
<div style={{ marginTop: "40px" }}>
<OnboardingGuide
visible={isOnboardingMode}
config={onboardingConfig}
onPromptSelect={onOnboardingPromptSelect}
completedSteps={completedOnboardingSteps}
skippedSteps={skippedOnboardingSteps}
currentStep={
onboardingConfig?.progress?.completed_tasks ||
(completedOnboardingSteps ? completedOnboardingSteps.size : 0)
}
totalSteps={onboardingConfig ? onboardingConfig.totalSteps : 4}
onSkip={onSkipOnboarding}
onComplete={onOnboardingComplete}
onSkipCurrentTask={onSkipCurrentTask}
currentOnboardingStep={currentOnboardingStep}
showWelcome={false}
hideModeTag={true}
collapsibleTodos={true}
/>
</div>
<TodoGuide
visible={isTodoGuideVisible && !isOnboardingMode}
onPromptSelect={handlePromptSelect}
completedTasks={completedTodoTasks}
onCompletedTasksChange={onCompletedTodoTasksChange}
/>
{/* Onboarding Completion Popup */}
<OnboardingCompletionPopup
visible={showCompletionPopup}
onClose={handleCompletionPopupClose}
onContinue={handleCompletionPopupContinue}
/>
<InputPrompt
savePrompt={handleSavePrompt}
isPromptRunning={isPromptRunning}
chatIntents={chatIntents}
selectedChatIntent={selectedChatIntent}
setSelectedChatIntent={setSelectedChatIntent}
llmModels={llmModels}
selectedLlmModel={selectedLlmModel}
setSelectedLlmModel={setSelectedLlmModel}
selectedCoderLlmModel={selectedCoderLlmModel}
setSelectedCoderLlmModel={setSelectedCoderLlmModel}
stopPromptRun={stopPromptRun}
selectedChatId={selectedChatId}
lastChatMessageId={lastChatMessageId}
promptAutoComplete={promptAutoComplete}
isChatConversationDisabled={isChatConversationDisabled}
prefilledPrompt={selectedPrompt}
shouldHighlightSend={
!!(isOnboardingMode && !isTypingPrompt && selectedPrompt)
}
isOnboardingMode={isOnboardingMode}
isTypingPrompt={isTypingPrompt}
disableSendDuringTyping={isOnboardingMode && isTypingPrompt}
onSendButtonClick={onSendButtonClick}
/>
</div>
</div>
);
});
ExistingChat.propTypes = {
selectedChatId: PropTypes.string,
chatName: PropTypes.string,
setChatName: PropTypes.func.isRequired,
savePrompt: PropTypes.func.isRequired,
chatMessages: PropTypes.array,
setChatMessages: PropTypes.func.isRequired,
isGetChatMessages: PropTypes.bool.isRequired,
resetChatMessageIdentifier: PropTypes.func.isRequired,
isPromptRunning: PropTypes.bool.isRequired,
chatIntents: PropTypes.array.isRequired,
selectedChatIntent: PropTypes.string,
setSelectedChatIntent: PropTypes.func.isRequired,
llmModels: PropTypes.array,
selectedLlmModel: PropTypes.string,
setSelectedLlmModel: PropTypes.func.isRequired,
selectedCoderLlmModel: PropTypes.string,
setSelectedCoderLlmModel: PropTypes.func.isRequired,
handleTransformApply: PropTypes.func.isRequired,
triggerRetryTransform: PropTypes.bool.isRequired,
stopPromptRun: PropTypes.func.isRequired,
handleSqlRun: PropTypes.func.isRequired,
promptAutoComplete: PropTypes.object,
isChatConversationDisabled: PropTypes.bool.isRequired,
tokenUsageData: PropTypes.object,
isTodoGuideVisible: PropTypes.bool,
onPromptSelect: PropTypes.func,
selectedPrompt: PropTypes.string,
completedTodoTasks: PropTypes.instanceOf(Set),
onCompletedTodoTasksChange: PropTypes.func,
// Onboarding props
isOnboardingMode: PropTypes.bool,
onboardingConfig: PropTypes.object,
completedOnboardingSteps: PropTypes.instanceOf(Set),
skippedOnboardingSteps: PropTypes.instanceOf(Set),
currentOnboardingStep: PropTypes.object,
isTypingPrompt: PropTypes.bool,
onOnboardingPromptSelect: PropTypes.func,
onSkipOnboarding: PropTypes.func,
onOnboardingComplete: PropTypes.func,
onSkipCurrentTask: PropTypes.func,
onSendButtonClick: PropTypes.func,
};
ExistingChat.displayName = "ExistingChat";
export { ExistingChat };