@sveda-ai/chat 0.3.1
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/LICENSE +557 -0
- package/README.md +18 -0
- package/dist/appearance.d.ts +54 -0
- package/dist/appearance.d.ts.map +1 -0
- package/dist/appearance.js +516 -0
- package/dist/appearance.js.map +1 -0
- package/dist/chatStore.d.ts +60 -0
- package/dist/chatStore.d.ts.map +1 -0
- package/dist/chatStore.js +518 -0
- package/dist/chatStore.js.map +1 -0
- package/dist/i18n/catalogs.d.ts +4 -0
- package/dist/i18n/catalogs.d.ts.map +1 -0
- package/dist/i18n/catalogs.js +3 -0
- package/dist/i18n/catalogs.js.map +1 -0
- package/dist/i18n/locales/en.d.ts +4 -0
- package/dist/i18n/locales/en.d.ts.map +1 -0
- package/dist/i18n/locales/en.js +59 -0
- package/dist/i18n/locales/en.js.map +1 -0
- package/dist/i18n/locales/ru.d.ts +4 -0
- package/dist/i18n/locales/ru.d.ts.map +1 -0
- package/dist/i18n/locales/ru.js +59 -0
- package/dist/i18n/locales/ru.js.map +1 -0
- package/dist/i18n/types.d.ts +2 -0
- package/dist/i18n/types.d.ts.map +1 -0
- package/dist/i18n/types.js +2 -0
- package/dist/i18n/types.js.map +1 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +19 -0
- package/dist/index.js.map +1 -0
- package/dist/lib/assistantMessage.d.ts +90 -0
- package/dist/lib/assistantMessage.d.ts.map +1 -0
- package/dist/lib/assistantMessage.js +311 -0
- package/dist/lib/assistantMessage.js.map +1 -0
- package/dist/lib/chatHistoryMerge.d.ts +20 -0
- package/dist/lib/chatHistoryMerge.d.ts.map +1 -0
- package/dist/lib/chatHistoryMerge.js +61 -0
- package/dist/lib/chatHistoryMerge.js.map +1 -0
- package/dist/lib/chatI18nKeys.d.ts +2 -0
- package/dist/lib/chatI18nKeys.d.ts.map +1 -0
- package/dist/lib/chatI18nKeys.js +63 -0
- package/dist/lib/chatI18nKeys.js.map +1 -0
- package/dist/lib/chatMessageVisibility.d.ts +6 -0
- package/dist/lib/chatMessageVisibility.d.ts.map +1 -0
- package/dist/lib/chatMessageVisibility.js +68 -0
- package/dist/lib/chatMessageVisibility.js.map +1 -0
- package/dist/lib/chatResize.d.ts +42 -0
- package/dist/lib/chatResize.d.ts.map +1 -0
- package/dist/lib/chatResize.js +71 -0
- package/dist/lib/chatResize.js.map +1 -0
- package/dist/lib/chatTabs.d.ts +9 -0
- package/dist/lib/chatTabs.d.ts.map +1 -0
- package/dist/lib/chatTabs.js +34 -0
- package/dist/lib/chatTabs.js.map +1 -0
- package/dist/lib/chatTitle.d.ts +3 -0
- package/dist/lib/chatTitle.d.ts.map +1 -0
- package/dist/lib/chatTitle.js +25 -0
- package/dist/lib/chatTitle.js.map +1 -0
- package/dist/lib/chatUiStorage.d.ts +6 -0
- package/dist/lib/chatUiStorage.d.ts.map +1 -0
- package/dist/lib/chatUiStorage.js +61 -0
- package/dist/lib/chatUiStorage.js.map +1 -0
- package/dist/lib/finalizeMessages.d.ts +21 -0
- package/dist/lib/finalizeMessages.d.ts.map +1 -0
- package/dist/lib/finalizeMessages.js +54 -0
- package/dist/lib/finalizeMessages.js.map +1 -0
- package/dist/lib/markdown.d.ts +8 -0
- package/dist/lib/markdown.d.ts.map +1 -0
- package/dist/lib/markdown.js +69 -0
- package/dist/lib/markdown.js.map +1 -0
- package/dist/lib/modelLabels.d.ts +3 -0
- package/dist/lib/modelLabels.d.ts.map +1 -0
- package/dist/lib/modelLabels.js +23 -0
- package/dist/lib/modelLabels.js.map +1 -0
- package/dist/lib/toolConfirmation.d.ts +11 -0
- package/dist/lib/toolConfirmation.d.ts.map +1 -0
- package/dist/lib/toolConfirmation.js +16 -0
- package/dist/lib/toolConfirmation.js.map +1 -0
- package/dist/lib/userMessage.d.ts +17 -0
- package/dist/lib/userMessage.d.ts.map +1 -0
- package/dist/lib/userMessage.js +33 -0
- package/dist/lib/userMessage.js.map +1 -0
- package/dist/streaming.d.ts +59 -0
- package/dist/streaming.d.ts.map +1 -0
- package/dist/streaming.js +375 -0
- package/dist/streaming.js.map +1 -0
- package/package.json +53 -0
- package/src/appearance.ts +654 -0
- package/src/chatStore.ts +696 -0
- package/src/i18n/catalogs.ts +3 -0
- package/src/i18n/locales/en.ts +64 -0
- package/src/i18n/locales/ru.ts +65 -0
- package/src/i18n/types.ts +1 -0
- package/src/index.ts +84 -0
- package/src/lib/assistantMessage.ts +439 -0
- package/src/lib/chatHistoryMerge.ts +93 -0
- package/src/lib/chatI18nKeys.ts +64 -0
- package/src/lib/chatMessageVisibility.ts +92 -0
- package/src/lib/chatResize.ts +123 -0
- package/src/lib/chatTabs.ts +54 -0
- package/src/lib/chatTitle.ts +30 -0
- package/src/lib/chatUiStorage.ts +69 -0
- package/src/lib/finalizeMessages.ts +81 -0
- package/src/lib/markdown.ts +90 -0
- package/src/lib/modelLabels.ts +24 -0
- package/src/lib/toolConfirmation.ts +31 -0
- package/src/lib/userMessage.ts +55 -0
- package/src/streaming.ts +514 -0
package/src/chatStore.ts
ADDED
|
@@ -0,0 +1,696 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createMessageId,
|
|
3
|
+
type SvedaChatHistorySummary,
|
|
4
|
+
type SvedaClient,
|
|
5
|
+
type SvedaDisplayMessage,
|
|
6
|
+
} from '@sveda-ai/core';
|
|
7
|
+
import {
|
|
8
|
+
mergeServerChatHistories,
|
|
9
|
+
resolveMergedCurrentChat,
|
|
10
|
+
upsertChatHistoryMessages,
|
|
11
|
+
} from './lib/chatHistoryMerge.js';
|
|
12
|
+
import { readPersistedMinimized, writePersistedMinimized } from './lib/chatUiStorage.js';
|
|
13
|
+
import {
|
|
14
|
+
finalizeMessagesForDisplay,
|
|
15
|
+
type SvedaFinalizableMessage,
|
|
16
|
+
} from './lib/finalizeMessages.js';
|
|
17
|
+
import { getUserMessageAttachmentNames, getUserMessageText } from './lib/userMessage.js';
|
|
18
|
+
|
|
19
|
+
export interface SvedaChatHistory {
|
|
20
|
+
id: string;
|
|
21
|
+
title: string;
|
|
22
|
+
preview?: string;
|
|
23
|
+
messages: SvedaDisplayMessage[];
|
|
24
|
+
tokensUsed: number;
|
|
25
|
+
contextWindowTokens: number;
|
|
26
|
+
createdAt: number;
|
|
27
|
+
updatedAt: number;
|
|
28
|
+
messagesLoaded: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface SvedaChatState {
|
|
32
|
+
isOpen: boolean;
|
|
33
|
+
isMinimized: boolean;
|
|
34
|
+
currentChatId: string | null;
|
|
35
|
+
isLoading: boolean;
|
|
36
|
+
isLoadingChatHistory: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface SvedaChatStoreSnapshot {
|
|
40
|
+
chatState: SvedaChatState;
|
|
41
|
+
currentChat: SvedaChatHistory | null;
|
|
42
|
+
chatHistories: SvedaChatHistory[];
|
|
43
|
+
openChatTabIds: string[];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export type SvedaChatTranslate = (key: string) => string;
|
|
47
|
+
|
|
48
|
+
export interface SvedaChatStoreOptions {
|
|
49
|
+
embedAuthEvent?: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface SvedaChatStore {
|
|
53
|
+
getState(): SvedaChatStoreSnapshot;
|
|
54
|
+
subscribe(listener: () => void): () => void;
|
|
55
|
+
setClient(client: SvedaClient | null): void;
|
|
56
|
+
getClient(): SvedaClient | null;
|
|
57
|
+
setTranslate(translate: SvedaChatTranslate | undefined): void;
|
|
58
|
+
loadHistories(): Promise<void>;
|
|
59
|
+
createNewChat(translate?: SvedaChatTranslate): string;
|
|
60
|
+
setCurrentChat(chatId: string, translate?: SvedaChatTranslate): Promise<void>;
|
|
61
|
+
addMessage(chatId: string, message: SvedaDisplayMessage): SvedaDisplayMessage | null;
|
|
62
|
+
setChatTitle(chatId: string, title: string): void;
|
|
63
|
+
refreshChatTitleFromServer(chatId: string): Promise<string | null>;
|
|
64
|
+
updateMessage(
|
|
65
|
+
chatId: string,
|
|
66
|
+
messageId: string,
|
|
67
|
+
updates: Partial<SvedaDisplayMessage>
|
|
68
|
+
): SvedaDisplayMessage | null;
|
|
69
|
+
setChatMessages(chatId: string, messages: SvedaDisplayMessage[]): void;
|
|
70
|
+
incrementChatTokens(chatId: string, tokens: number): void;
|
|
71
|
+
setChatContextWindowTokens(chatId: string, tokens: number): void;
|
|
72
|
+
deleteChat(chatId: string, translate?: SvedaChatTranslate): void;
|
|
73
|
+
renameChat(chatId: string, title: string): void;
|
|
74
|
+
closeChatTab(chatId: string, translate?: SvedaChatTranslate): Promise<void>;
|
|
75
|
+
openChat(translate?: SvedaChatTranslate): Promise<void>;
|
|
76
|
+
closeChat(): void;
|
|
77
|
+
minimizeChat(): void;
|
|
78
|
+
maximizeChat(): void;
|
|
79
|
+
setLoading(loading: boolean): void;
|
|
80
|
+
sortedHistories(): SvedaChatHistory[];
|
|
81
|
+
openChatTabs(): SvedaChatHistory[];
|
|
82
|
+
initAuthListener(): void;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const hasUserRequests = (chat: SvedaChatHistory): boolean => {
|
|
86
|
+
if (typeof chat.preview === 'string' && chat.preview.trim().length > 0) {
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return chat.messages.some(message => {
|
|
91
|
+
if (message.role !== 'user') {
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const body = getUserMessageText(message);
|
|
96
|
+
const hasFiles = getUserMessageAttachmentNames(message).length > 0;
|
|
97
|
+
return body.length > 0 || hasFiles;
|
|
98
|
+
});
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const isServerSummary = (chat: SvedaChatHistory): boolean => !chat.messagesLoaded;
|
|
102
|
+
|
|
103
|
+
const shouldIncludeInHistoryList = (chat: SvedaChatHistory): boolean =>
|
|
104
|
+
hasUserRequests(chat) || isServerSummary(chat);
|
|
105
|
+
|
|
106
|
+
const generateChatId = (): string => `chat_${createMessageId()}`;
|
|
107
|
+
|
|
108
|
+
const toTimestamp = (value: unknown): number => {
|
|
109
|
+
if (typeof value === 'number' && Number.isFinite(value)) {
|
|
110
|
+
return value;
|
|
111
|
+
}
|
|
112
|
+
if (typeof value === 'string') {
|
|
113
|
+
const parsed = Date.parse(value);
|
|
114
|
+
if (!Number.isNaN(parsed)) {
|
|
115
|
+
return parsed;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return Date.now();
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
const finalizeForDisplay = (messages: unknown): SvedaDisplayMessage[] => {
|
|
122
|
+
const list = Array.isArray(messages) ? (messages as SvedaFinalizableMessage[]) : [];
|
|
123
|
+
return finalizeMessagesForDisplay(list) as unknown as SvedaDisplayMessage[];
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
const resolveServerHistoryId = (history: SvedaChatHistorySummary): string => {
|
|
127
|
+
const fromChatId = typeof history.chatId === 'string' ? history.chatId.trim() : '';
|
|
128
|
+
if (fromChatId !== '') {
|
|
129
|
+
return fromChatId;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const fromId = typeof history.id === 'string' ? history.id.trim() : '';
|
|
133
|
+
return fromId;
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const mapServerHistory = (
|
|
137
|
+
history: SvedaChatHistorySummary & { messages?: unknown },
|
|
138
|
+
messagesLoaded: boolean
|
|
139
|
+
): SvedaChatHistory => ({
|
|
140
|
+
id: resolveServerHistoryId(history),
|
|
141
|
+
title: history.title || '',
|
|
142
|
+
preview: typeof history.preview === 'string' ? history.preview : '',
|
|
143
|
+
messages: messagesLoaded ? finalizeForDisplay(history.messages) : [],
|
|
144
|
+
tokensUsed: Number(history.tokensUsed) || 0,
|
|
145
|
+
contextWindowTokens: Number(history.contextWindowTokens) || 0,
|
|
146
|
+
createdAt: toTimestamp(history.createdAt),
|
|
147
|
+
updatedAt: toTimestamp(history.updatedAt),
|
|
148
|
+
messagesLoaded,
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
const buildWelcomeMessage = (text: string): SvedaDisplayMessage => ({
|
|
152
|
+
id: createMessageId(),
|
|
153
|
+
role: 'assistant',
|
|
154
|
+
parts: [{ type: 'text', text }],
|
|
155
|
+
createdAt: new Date().toISOString(),
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
export function createSvedaChatStore(options: SvedaChatStoreOptions = {}): SvedaChatStore {
|
|
159
|
+
const embedAuthEvent = options.embedAuthEvent ?? 'sveda-embed-auth';
|
|
160
|
+
const listeners = new Set<() => void>();
|
|
161
|
+
|
|
162
|
+
const initialIsMinimized = readPersistedMinimized();
|
|
163
|
+
const chatState: SvedaChatState = {
|
|
164
|
+
isOpen: !initialIsMinimized,
|
|
165
|
+
isMinimized: initialIsMinimized,
|
|
166
|
+
currentChatId: null,
|
|
167
|
+
isLoading: false,
|
|
168
|
+
isLoadingChatHistory: false,
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
let currentChat: SvedaChatHistory | null = null;
|
|
172
|
+
let chatHistories: SvedaChatHistory[] = [];
|
|
173
|
+
let openChatTabIds: string[] = [];
|
|
174
|
+
let activeClient: SvedaClient | null = null;
|
|
175
|
+
let translateFn: SvedaChatTranslate | undefined;
|
|
176
|
+
let authListenerBound = false;
|
|
177
|
+
|
|
178
|
+
const notify = () => {
|
|
179
|
+
for (const listener of listeners) {
|
|
180
|
+
listener();
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
const getState = (): SvedaChatStoreSnapshot => ({
|
|
185
|
+
chatState: { ...chatState },
|
|
186
|
+
currentChat,
|
|
187
|
+
chatHistories,
|
|
188
|
+
openChatTabIds: [...openChatTabIds],
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
const subscribe = (listener: () => void): (() => void) => {
|
|
192
|
+
listeners.add(listener);
|
|
193
|
+
return () => {
|
|
194
|
+
listeners.delete(listener);
|
|
195
|
+
};
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
const ensureChatTab = (chatId: string) => {
|
|
199
|
+
if (!openChatTabIds.includes(chatId)) {
|
|
200
|
+
openChatTabIds = [...openChatTabIds, chatId];
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
const removeChatTab = (chatId: string) => {
|
|
205
|
+
openChatTabIds = openChatTabIds.filter(id => id !== chatId);
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
const historiesEndpointConfigured = (): boolean => Boolean(activeClient?.endpoints.histories);
|
|
209
|
+
|
|
210
|
+
const embedAuthReady = (): boolean => {
|
|
211
|
+
if (!activeClient || activeClient.credentials !== 'omit') {
|
|
212
|
+
return true;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const headers = activeClient.resolveHeaders();
|
|
216
|
+
return Boolean(
|
|
217
|
+
headers['X-Sveda-Embed-Token'] ||
|
|
218
|
+
headers['x-sveda-embed-token'] ||
|
|
219
|
+
headers.Authorization ||
|
|
220
|
+
headers.authorization
|
|
221
|
+
);
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
const fetchHistoriesFromServer = async (): Promise<SvedaChatHistory[]> => {
|
|
225
|
+
if (!activeClient || !historiesEndpointConfigured() || !embedAuthReady()) {
|
|
226
|
+
return [];
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
try {
|
|
230
|
+
const histories = await activeClient.listHistories();
|
|
231
|
+
return histories.map(history => mapServerHistory(history, false));
|
|
232
|
+
} catch (err) {
|
|
233
|
+
console.error('Error loading chat histories from server:', err);
|
|
234
|
+
return [];
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
const fetchChatHistoryFromServer = async (chatId: string): Promise<SvedaChatHistory | null> => {
|
|
239
|
+
if (!activeClient || !historiesEndpointConfigured() || !embedAuthReady()) {
|
|
240
|
+
return null;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
try {
|
|
244
|
+
const detail = await activeClient.getHistory(chatId);
|
|
245
|
+
return mapServerHistory(detail, true);
|
|
246
|
+
} catch (err) {
|
|
247
|
+
console.error('Error loading chat history from server:', err);
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
const deleteChatOnServer = async (chatId: string) => {
|
|
253
|
+
if (!activeClient || !historiesEndpointConfigured() || !embedAuthReady()) {
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
try {
|
|
258
|
+
await activeClient.deleteHistory(chatId);
|
|
259
|
+
} catch (err) {
|
|
260
|
+
console.error('Error deleting chat history from server:', err);
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
const renameChatOnServer = async (chatId: string, title: string) => {
|
|
265
|
+
if (!activeClient || !historiesEndpointConfigured() || !embedAuthReady()) {
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
try {
|
|
270
|
+
await activeClient.renameHistory(chatId, title);
|
|
271
|
+
} catch (err) {
|
|
272
|
+
console.error('Error renaming chat history on server:', err);
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
const sortedHistories = (): SvedaChatHistory[] =>
|
|
277
|
+
[...chatHistories].filter(shouldIncludeInHistoryList).sort((a, b) => b.updatedAt - a.updatedAt);
|
|
278
|
+
|
|
279
|
+
const openChatTabs = (): SvedaChatHistory[] => {
|
|
280
|
+
const ids = [...openChatTabIds];
|
|
281
|
+
if (currentChat?.id && !ids.includes(currentChat.id)) {
|
|
282
|
+
ids.push(currentChat.id);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
return ids
|
|
286
|
+
.map(id => chatHistories.find(chat => chat.id === id))
|
|
287
|
+
.filter((chat): chat is SvedaChatHistory => !!chat);
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
const loadChatHistoryIfNeeded = async (chatId: string): Promise<boolean> => {
|
|
291
|
+
const chatIndex = chatHistories.findIndex(c => c.id === chatId);
|
|
292
|
+
if (chatIndex === -1) {
|
|
293
|
+
return false;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const chat = chatHistories[chatIndex];
|
|
297
|
+
if (chat.messagesLoaded) {
|
|
298
|
+
return true;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const loadedHistory = await fetchChatHistoryFromServer(chatId);
|
|
302
|
+
if (!loadedHistory) {
|
|
303
|
+
return false;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
chatHistories[chatIndex] = {
|
|
307
|
+
...loadedHistory,
|
|
308
|
+
preview: chat.preview || loadedHistory.preview,
|
|
309
|
+
};
|
|
310
|
+
chatHistories = [...chatHistories];
|
|
311
|
+
notify();
|
|
312
|
+
return true;
|
|
313
|
+
};
|
|
314
|
+
|
|
315
|
+
const setCurrentChat = async (chatId: string, translate?: SvedaChatTranslate) => {
|
|
316
|
+
const t = translate ?? translateFn;
|
|
317
|
+
chatState.isLoadingChatHistory = true;
|
|
318
|
+
notify();
|
|
319
|
+
try {
|
|
320
|
+
await loadChatHistoryIfNeeded(chatId);
|
|
321
|
+
|
|
322
|
+
const chatIndex = chatHistories.findIndex(c => c.id === chatId);
|
|
323
|
+
const chat = chatIndex === -1 ? undefined : chatHistories[chatIndex];
|
|
324
|
+
if (chat) {
|
|
325
|
+
chatHistories[chatIndex] = {
|
|
326
|
+
...chat,
|
|
327
|
+
messages: finalizeForDisplay(chat.messages),
|
|
328
|
+
};
|
|
329
|
+
chatHistories = [...chatHistories];
|
|
330
|
+
currentChat = chatHistories[chatIndex];
|
|
331
|
+
chatState.currentChatId = chatId;
|
|
332
|
+
ensureChatTab(chatId);
|
|
333
|
+
if (currentChat.messages.length === 0 && t) {
|
|
334
|
+
const welcomeText = t('welcomeMessage');
|
|
335
|
+
if (welcomeText) {
|
|
336
|
+
currentChat.messages.push(buildWelcomeMessage(welcomeText));
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
} finally {
|
|
341
|
+
chatState.isLoadingChatHistory = false;
|
|
342
|
+
notify();
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
|
|
346
|
+
const createNewChat = (translate?: SvedaChatTranslate): string => {
|
|
347
|
+
const t = translate ?? translateFn;
|
|
348
|
+
const chatId = generateChatId();
|
|
349
|
+
const welcomeText = t ? t('welcomeMessage') : '';
|
|
350
|
+
const newChatTitle = t ? t('newChat') : 'New Chat';
|
|
351
|
+
|
|
352
|
+
const newChat: SvedaChatHistory = {
|
|
353
|
+
id: chatId,
|
|
354
|
+
title: newChatTitle,
|
|
355
|
+
preview: '',
|
|
356
|
+
messages: welcomeText ? [buildWelcomeMessage(welcomeText)] : [],
|
|
357
|
+
tokensUsed: 0,
|
|
358
|
+
contextWindowTokens: 0,
|
|
359
|
+
createdAt: Date.now(),
|
|
360
|
+
updatedAt: Date.now(),
|
|
361
|
+
messagesLoaded: true,
|
|
362
|
+
};
|
|
363
|
+
|
|
364
|
+
chatHistories = [newChat, ...chatHistories];
|
|
365
|
+
currentChat = newChat;
|
|
366
|
+
chatState.currentChatId = chatId;
|
|
367
|
+
ensureChatTab(chatId);
|
|
368
|
+
notify();
|
|
369
|
+
void setCurrentChat(chatId, t);
|
|
370
|
+
|
|
371
|
+
return chatId;
|
|
372
|
+
};
|
|
373
|
+
|
|
374
|
+
const loadHistories = async () => {
|
|
375
|
+
const serverHistories = await fetchHistoriesFromServer();
|
|
376
|
+
|
|
377
|
+
chatHistories = mergeServerChatHistories(serverHistories, currentChat);
|
|
378
|
+
currentChat = resolveMergedCurrentChat(chatHistories, currentChat);
|
|
379
|
+
if (currentChat) {
|
|
380
|
+
chatState.currentChatId = currentChat.id;
|
|
381
|
+
}
|
|
382
|
+
notify();
|
|
383
|
+
|
|
384
|
+
if (chatHistories.length > 0 && !currentChat) {
|
|
385
|
+
const latest = [...chatHistories].sort((a, b) => b.updatedAt - a.updatedAt)[0];
|
|
386
|
+
await setCurrentChat(latest.id);
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
|
|
390
|
+
const addMessage = (chatId: string, message: SvedaDisplayMessage): SvedaDisplayMessage | null => {
|
|
391
|
+
const chatIndex = chatHistories.findIndex(c => c.id === chatId);
|
|
392
|
+
if (chatIndex === -1) {
|
|
393
|
+
return null;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
const chat = chatHistories[chatIndex];
|
|
397
|
+
if (!message.createdAt) {
|
|
398
|
+
message.createdAt = new Date().toISOString();
|
|
399
|
+
}
|
|
400
|
+
if (!message.id) {
|
|
401
|
+
message.id = createMessageId();
|
|
402
|
+
}
|
|
403
|
+
chat.messages = [...chat.messages, message];
|
|
404
|
+
chat.messagesLoaded = true;
|
|
405
|
+
chat.updatedAt = Date.now();
|
|
406
|
+
chatHistories = [...chatHistories];
|
|
407
|
+
|
|
408
|
+
if (currentChat?.id === chatId) {
|
|
409
|
+
currentChat = chatHistories[chatIndex];
|
|
410
|
+
}
|
|
411
|
+
notify();
|
|
412
|
+
return message;
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
const setChatTitle = (chatId: string, title: string) => {
|
|
416
|
+
const normalizedTitle = title.trim();
|
|
417
|
+
if (!normalizedTitle) {
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
const chatIndex = chatHistories.findIndex(c => c.id === chatId);
|
|
422
|
+
if (chatIndex === -1) {
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
const chat = chatHistories[chatIndex];
|
|
427
|
+
chat.title = normalizedTitle;
|
|
428
|
+
chat.updatedAt = Date.now();
|
|
429
|
+
chatHistories = [...chatHistories];
|
|
430
|
+
|
|
431
|
+
if (currentChat?.id === chatId) {
|
|
432
|
+
currentChat = chatHistories[chatIndex];
|
|
433
|
+
}
|
|
434
|
+
notify();
|
|
435
|
+
};
|
|
436
|
+
|
|
437
|
+
const incrementChatTokens = (chatId: string, tokens: number) => {
|
|
438
|
+
const normalizedTokens = Number(tokens);
|
|
439
|
+
if (!Number.isFinite(normalizedTokens) || normalizedTokens <= 0) {
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
const chatIndex = chatHistories.findIndex(c => c.id === chatId);
|
|
444
|
+
if (chatIndex === -1) {
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
const chat = chatHistories[chatIndex];
|
|
449
|
+
chat.tokensUsed = Math.max(0, Number(chat.tokensUsed || 0) + Math.floor(normalizedTokens));
|
|
450
|
+
chat.updatedAt = Date.now();
|
|
451
|
+
chatHistories = [...chatHistories];
|
|
452
|
+
|
|
453
|
+
if (currentChat?.id === chatId) {
|
|
454
|
+
currentChat = chatHistories[chatIndex];
|
|
455
|
+
}
|
|
456
|
+
notify();
|
|
457
|
+
};
|
|
458
|
+
|
|
459
|
+
const setChatContextWindowTokens = (chatId: string, tokens: number) => {
|
|
460
|
+
const normalizedTokens = Number(tokens);
|
|
461
|
+
if (!Number.isFinite(normalizedTokens) || normalizedTokens < 0) {
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
const chatIndex = chatHistories.findIndex(c => c.id === chatId);
|
|
466
|
+
if (chatIndex === -1) {
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
const chat = chatHistories[chatIndex];
|
|
471
|
+
chat.contextWindowTokens = Math.max(0, Math.floor(normalizedTokens));
|
|
472
|
+
chatHistories = [...chatHistories];
|
|
473
|
+
|
|
474
|
+
if (currentChat?.id === chatId) {
|
|
475
|
+
currentChat = chatHistories[chatIndex];
|
|
476
|
+
}
|
|
477
|
+
notify();
|
|
478
|
+
};
|
|
479
|
+
|
|
480
|
+
const updateMessage = (
|
|
481
|
+
chatId: string,
|
|
482
|
+
messageId: string,
|
|
483
|
+
updates: Partial<SvedaDisplayMessage>
|
|
484
|
+
): SvedaDisplayMessage | null => {
|
|
485
|
+
const chatIndex = chatHistories.findIndex(c => c.id === chatId);
|
|
486
|
+
if (chatIndex === -1) {
|
|
487
|
+
return null;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
const chat = chatHistories[chatIndex];
|
|
491
|
+
const messageIndex = chat.messages.findIndex(m => m.id === messageId);
|
|
492
|
+
if (messageIndex === -1) {
|
|
493
|
+
return null;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
const updatedMessage = {
|
|
497
|
+
...chat.messages[messageIndex],
|
|
498
|
+
...updates,
|
|
499
|
+
};
|
|
500
|
+
chat.messages.splice(messageIndex, 1, updatedMessage);
|
|
501
|
+
chat.updatedAt = Date.now();
|
|
502
|
+
chatHistories = [...chatHistories];
|
|
503
|
+
|
|
504
|
+
if (currentChat?.id === chatId) {
|
|
505
|
+
currentChat = chatHistories[chatIndex];
|
|
506
|
+
}
|
|
507
|
+
notify();
|
|
508
|
+
return updatedMessage;
|
|
509
|
+
};
|
|
510
|
+
|
|
511
|
+
const setChatMessages = (chatId: string, messages: SvedaDisplayMessage[]) => {
|
|
512
|
+
const result = upsertChatHistoryMessages(
|
|
513
|
+
chatHistories,
|
|
514
|
+
currentChat,
|
|
515
|
+
chatId,
|
|
516
|
+
finalizeForDisplay(messages)
|
|
517
|
+
);
|
|
518
|
+
|
|
519
|
+
chatHistories = result.histories;
|
|
520
|
+
currentChat = result.current;
|
|
521
|
+
if (result.current?.id === chatId) {
|
|
522
|
+
chatState.currentChatId = chatId;
|
|
523
|
+
ensureChatTab(chatId);
|
|
524
|
+
}
|
|
525
|
+
notify();
|
|
526
|
+
};
|
|
527
|
+
|
|
528
|
+
const deleteChat = (chatId: string, translate?: SvedaChatTranslate) => {
|
|
529
|
+
const t = translate ?? translateFn;
|
|
530
|
+
const index = chatHistories.findIndex(c => c.id === chatId);
|
|
531
|
+
if (index === -1) {
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
chatHistories = chatHistories.filter(c => c.id !== chatId);
|
|
536
|
+
removeChatTab(chatId);
|
|
537
|
+
void deleteChatOnServer(chatId);
|
|
538
|
+
notify();
|
|
539
|
+
|
|
540
|
+
if (chatState.currentChatId === chatId) {
|
|
541
|
+
if (chatHistories.length > 0) {
|
|
542
|
+
void setCurrentChat(chatHistories[0].id, t);
|
|
543
|
+
} else {
|
|
544
|
+
createNewChat(t);
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
};
|
|
548
|
+
|
|
549
|
+
const renameChat = (chatId: string, title: string) => {
|
|
550
|
+
const normalizedTitle = title.trim();
|
|
551
|
+
if (!normalizedTitle) {
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
setChatTitle(chatId, normalizedTitle);
|
|
556
|
+
void renameChatOnServer(chatId, normalizedTitle);
|
|
557
|
+
};
|
|
558
|
+
|
|
559
|
+
const closeChatTab = async (chatId: string, translate?: SvedaChatTranslate) => {
|
|
560
|
+
const t = translate ?? translateFn;
|
|
561
|
+
const currentIndex = openChatTabIds.findIndex(id => id === chatId);
|
|
562
|
+
removeChatTab(chatId);
|
|
563
|
+
notify();
|
|
564
|
+
|
|
565
|
+
if (currentChat?.id !== chatId) {
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
const nextChatId =
|
|
570
|
+
openChatTabIds[currentIndex] ||
|
|
571
|
+
openChatTabIds[currentIndex - 1] ||
|
|
572
|
+
sortedHistories().find(chat => chat.id !== chatId)?.id;
|
|
573
|
+
|
|
574
|
+
if (nextChatId) {
|
|
575
|
+
await setCurrentChat(nextChatId, t);
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
createNewChat(t);
|
|
580
|
+
};
|
|
581
|
+
|
|
582
|
+
const openChat = async (translate?: SvedaChatTranslate) => {
|
|
583
|
+
const t = translate ?? translateFn;
|
|
584
|
+
chatState.isOpen = true;
|
|
585
|
+
chatState.isMinimized = false;
|
|
586
|
+
writePersistedMinimized(false);
|
|
587
|
+
notify();
|
|
588
|
+
if (!currentChat && chatHistories.length === 0) {
|
|
589
|
+
createNewChat(t);
|
|
590
|
+
} else if (!currentChat && chatHistories.length > 0) {
|
|
591
|
+
await setCurrentChat(chatHistories[0].id, t);
|
|
592
|
+
}
|
|
593
|
+
};
|
|
594
|
+
|
|
595
|
+
const closeChat = () => {
|
|
596
|
+
chatState.isOpen = false;
|
|
597
|
+
chatState.isMinimized = true;
|
|
598
|
+
writePersistedMinimized(true);
|
|
599
|
+
notify();
|
|
600
|
+
};
|
|
601
|
+
|
|
602
|
+
const minimizeChat = () => {
|
|
603
|
+
chatState.isMinimized = true;
|
|
604
|
+
writePersistedMinimized(true);
|
|
605
|
+
notify();
|
|
606
|
+
};
|
|
607
|
+
|
|
608
|
+
const maximizeChat = () => {
|
|
609
|
+
chatState.isMinimized = false;
|
|
610
|
+
chatState.isOpen = true;
|
|
611
|
+
writePersistedMinimized(false);
|
|
612
|
+
notify();
|
|
613
|
+
};
|
|
614
|
+
|
|
615
|
+
const setLoading = (loading: boolean) => {
|
|
616
|
+
chatState.isLoading = loading;
|
|
617
|
+
notify();
|
|
618
|
+
};
|
|
619
|
+
|
|
620
|
+
const refreshChatTitleFromServer = async (chatId: string): Promise<string | null> => {
|
|
621
|
+
const loaded = await fetchChatHistoryFromServer(chatId);
|
|
622
|
+
if (!loaded) {
|
|
623
|
+
return null;
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
if (loaded.messages.length > 0) {
|
|
627
|
+
const current =
|
|
628
|
+
currentChat?.id === chatId
|
|
629
|
+
? currentChat
|
|
630
|
+
: chatHistories.find(chat => chat.id === chatId);
|
|
631
|
+
const localCount = current?.messages.length ?? 0;
|
|
632
|
+
if (loaded.messages.length >= localCount) {
|
|
633
|
+
setChatMessages(chatId, loaded.messages);
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
const title = loaded.title?.trim();
|
|
638
|
+
return title || null;
|
|
639
|
+
};
|
|
640
|
+
|
|
641
|
+
const initAuthListener = () => {
|
|
642
|
+
if (authListenerBound || typeof window === 'undefined') {
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
authListenerBound = true;
|
|
646
|
+
window.addEventListener(embedAuthEvent, () => {
|
|
647
|
+
if (historiesEndpointConfigured() && embedAuthReady()) {
|
|
648
|
+
void loadHistories();
|
|
649
|
+
}
|
|
650
|
+
});
|
|
651
|
+
};
|
|
652
|
+
|
|
653
|
+
return {
|
|
654
|
+
getState,
|
|
655
|
+
subscribe,
|
|
656
|
+
setClient(client) {
|
|
657
|
+
activeClient = client;
|
|
658
|
+
},
|
|
659
|
+
getClient() {
|
|
660
|
+
return activeClient;
|
|
661
|
+
},
|
|
662
|
+
setTranslate(translate) {
|
|
663
|
+
translateFn = translate;
|
|
664
|
+
},
|
|
665
|
+
loadHistories,
|
|
666
|
+
createNewChat,
|
|
667
|
+
setCurrentChat,
|
|
668
|
+
addMessage,
|
|
669
|
+
setChatTitle,
|
|
670
|
+
refreshChatTitleFromServer,
|
|
671
|
+
updateMessage,
|
|
672
|
+
setChatMessages,
|
|
673
|
+
incrementChatTokens,
|
|
674
|
+
setChatContextWindowTokens,
|
|
675
|
+
deleteChat,
|
|
676
|
+
renameChat,
|
|
677
|
+
closeChatTab,
|
|
678
|
+
openChat,
|
|
679
|
+
closeChat,
|
|
680
|
+
minimizeChat,
|
|
681
|
+
maximizeChat,
|
|
682
|
+
setLoading,
|
|
683
|
+
sortedHistories,
|
|
684
|
+
openChatTabs,
|
|
685
|
+
initAuthListener,
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
let sharedChatStore: SvedaChatStore | null = null;
|
|
690
|
+
|
|
691
|
+
export function getSvedaChatStore(options?: SvedaChatStoreOptions): SvedaChatStore {
|
|
692
|
+
if (!sharedChatStore) {
|
|
693
|
+
sharedChatStore = createSvedaChatStore(options);
|
|
694
|
+
}
|
|
695
|
+
return sharedChatStore;
|
|
696
|
+
}
|