forked from leojay-net/Stellar-Dex-Chat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseChatHistory.ts
More file actions
298 lines (256 loc) · 9.34 KB
/
Copy pathuseChatHistory.ts
File metadata and controls
298 lines (256 loc) · 9.34 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
'use client';
import { useState, useCallback, useEffect, useRef } from 'react';
import { ChatSession, ChatHistoryState, ChatMessage } from '@/types';
import { ChatHistoryManager } from '@/lib/chatHistory';
import { useStellarWallet } from '@/contexts/StellarWalletContext';
export const useChatHistory = () => {
const { connection } = useStellarWallet();
const [historyState, setHistoryState] = useState<ChatHistoryState>({
currentSessionId: null,
sessions: [],
});
const [isHistoryOpen, setIsHistoryOpen] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const [searchResults, setSearchResults] = useState<ChatSession[]>([]);
// Keep a ref to the latest sessions so callbacks that need to read (not write)
// sessions never capture a stale closure snapshot.
const sessionsRef = useRef<ChatSession[]>(historyState.sessions);
useEffect(() => {
sessionsRef.current = historyState.sessions;
}, [historyState.sessions]);
// Load history from localStorage on mount
useEffect(() => {
const loaded = ChatHistoryManager.loadFromLocalStorage();
setHistoryState(loaded);
}, []);
// Debounced save to localStorage
useEffect(() => {
if (historyState.sessions.length > 0) {
const timeoutId = setTimeout(() => {
ChatHistoryManager.saveToLocalStorage(historyState);
}, 500); // Debounce by 500ms
return () => clearTimeout(timeoutId);
}
}, [historyState]);
// Debounced search — avoids triggering a lookup on every keystroke
useEffect(() => {
if (!searchQuery.trim()) {
setSearchResults([]);
return;
}
const timeoutId = setTimeout(() => {
setSearchResults(
ChatHistoryManager.searchSessions(historyState.sessions, searchQuery),
);
}, 300);
return () => clearTimeout(timeoutId);
}, [searchQuery, historyState.sessions]);
const createNewSession = useCallback(
(initialMessages: ChatMessage[] = []): string => {
const newSession = ChatHistoryManager.createNewSession(
connection.address,
);
newSession.messages = [...initialMessages]; // Clone to prevent reference issues
setHistoryState((prev) => {
// Deduplicate before adding new session
const dedupedSessions = ChatHistoryManager.deduplicateSessions([
newSession,
...prev.sessions,
]);
const updatedSessions =
ChatHistoryManager.cleanupOldSessions(dedupedSessions);
return {
currentSessionId: newSession.id,
sessions: updatedSessions,
};
});
return newSession.id;
},
[connection.address],
);
const updateCurrentSession = useCallback(
(messages: ChatMessage[]) => {
// Race-condition fix (#1213): the previous implementation read
// `historyState.currentSessionId` from the closure, which could be stale
// if multiple state updates were in-flight. The early-return guard has
// been moved inside the functional updater so it always sees the latest
// committed state — no stale snapshot can cause a phantom update or a
// missed guard.
setHistoryState((prev) => {
setHistoryState((prev) => {
// Guard inside the functional updater so it always reads fresh state,
// not the stale closure value of historyState.currentSessionId (#1223).
if (!prev.currentSessionId) return prev;
const sessionIndex = prev.sessions.findIndex(
(s) => s.id === prev.currentSessionId,
);
if (sessionIndex === -1) return prev;
const updatedSession = {
...prev.sessions[sessionIndex],
messages,
lastUpdated: new Date(),
};
const updatedSessionWithTitle =
ChatHistoryManager.updateSessionTitle(updatedSession);
const updatedSessions = [...prev.sessions];
updatedSessions[sessionIndex] = updatedSessionWithTitle;
return {
...prev,
sessions: updatedSessions,
};
});
},
[],
);
const loadSession = useCallback(
(sessionId: string): ChatMessage[] | null => {
// Race-condition fix (#1213): reading `historyState.sessions` from the
// closure captured at useCallback creation could be a stale snapshot when
// rapid session switches occur. We now read from sessionsRef which is
// synchronously updated via a layout-effect-ordered ref, ensuring the
// lookup always reflects the latest committed sessions list.
const session = sessionsRef.current.find((s) => s.id === sessionId);
if (!session) return null;
setHistoryState((prev) => ({
...prev,
currentSessionId: sessionId,
}));
return session.messages;
},
[],
);
const deleteSession = useCallback((sessionId: string) => {
setHistoryState((prev) => {
const updatedSessions = prev.sessions.filter((s) => s.id !== sessionId);
const newCurrentSessionId =
prev.currentSessionId === sessionId ? null : prev.currentSessionId;
return {
currentSessionId: newCurrentSessionId,
sessions: updatedSessions,
};
});
}, []);
const clearAllHistory = useCallback(() => {
setHistoryState({
currentSessionId: null,
sessions: [],
});
localStorage.removeItem('defi_chat_history');
}, []);
const exportSession = useCallback(
(sessionId: string): string | null => {
const session = sessionsRef.current.find((s) => s.id === sessionId);
if (!session) return null;
return ChatHistoryManager.exportSession(session);
},
[],
);
const exportSessionAsJSON = useCallback(
(sessionId: string): { data: string; filename: string } | null => {
const session = sessionsRef.current.find((s) => s.id === sessionId);
if (!session) return null;
const data = ChatHistoryManager.exportSessionAsJSON(session);
const filename = ChatHistoryManager.generateExportFilename(sessionId, 'json');
return { data, filename };
},
[],
);
const exportSessionAsTXT = useCallback(
(sessionId: string): { data: string; filename: string } | null => {
const session = sessionsRef.current.find((s) => s.id === sessionId);
if (!session) return null;
const data = ChatHistoryManager.exportSessionAsTXT(session);
const filename = ChatHistoryManager.generateExportFilename(sessionId, 'txt');
return { data, filename };
},
[],
);
const searchSessions = useCallback(
(query: string): ChatSession[] => {
return ChatHistoryManager.searchSessions(sessionsRef.current, query);
},
[],
);
const getCurrentSession = useCallback((): ChatSession | null => {
if (!historyState.currentSessionId) return null;
return (
sessionsRef.current.find(
(s) => s.id === historyState.currentSessionId,
) || null
);
}, [historyState.currentSessionId]);
const togglePin = useCallback((sessionId: string) => {
setHistoryState((prev) => {
const idx = prev.sessions.findIndex((s) => s.id === sessionId);
if (idx === -1) return prev;
const session = prev.sessions[idx];
const nowPinned = !session.pinned;
const updatedSession: ChatSession = {
...session,
pinned: nowPinned,
pinnedAt: nowPinned ? new Date() : undefined,
};
const updated = [...prev.sessions];
updated[idx] = updatedSession;
return { ...prev, sessions: updated };
});
}, []);
const reorderPinned = useCallback((newPinnedOrder: string[]) => {
setHistoryState((prev) => {
const sessionsMap = new Map(prev.sessions.map((s) => [s.id, s]));
const pinnedCount = newPinnedOrder.length;
// Assign new pinnedAt timestamps to preserve ordering (newest first)
const now = Date.now();
const updated = [...prev.sessions];
newPinnedOrder.forEach((id, index) => {
const s = sessionsMap.get(id);
if (!s) return;
const updatedSession = { ...s, pinned: true, pinnedAt: new Date(now + (pinnedCount - index)) } as ChatSession;
const idx = updated.findIndex((ss) => ss.id === id);
if (idx !== -1) updated[idx] = updatedSession;
});
return { ...prev, sessions: updated };
});
}, []);
// Pinned sessions first (sorted by pinnedAt desc), then unpinned (by lastUpdated desc)
const sortedSessions = [...historyState.sessions].sort((a, b) => {
if (a.pinned && !b.pinned) return -1;
if (!a.pinned && b.pinned) return 1;
if (a.pinned && b.pinned) {
return (b.pinnedAt?.getTime() ?? 0) - (a.pinnedAt?.getTime() ?? 0);
}
return (
new Date(b.lastUpdated).getTime() - new Date(a.lastUpdated).getTime()
);
});
const pinnedSessions = sortedSessions.filter((s) => s.pinned);
const unpinnedSessions = sortedSessions.filter((s) => !s.pinned);
return {
// State
sessions: sortedSessions,
pinnedSessions,
unpinnedSessions,
currentSessionId: historyState.currentSessionId,
currentSession: getCurrentSession(),
isHistoryOpen,
// Actions
createNewSession,
updateCurrentSession,
loadSession,
deleteSession,
clearAllHistory,
reorderPinned,
exportSession,
exportSessionAsJSON,
exportSessionAsTXT,
searchSessions,
togglePin,
setIsHistoryOpen,
// Utils
hasHistory: historyState.sessions.length > 0,
// Debounced search
searchQuery,
setSearchQuery,
searchResults,
};
};