Messages.svelte 11 KB
Newer Older
1
2
3
<script lang="ts">
	import { v4 as uuidv4 } from 'uuid';

4
	import { chats, config, modelfiles, settings, user as _user, mobile } from '$lib/stores';
5
	import { tick, getContext } from 'svelte';
6

Jannik Streidl's avatar
Jannik Streidl committed
7
	import { toast } from 'svelte-sonner';
Timothy J. Baek's avatar
Timothy J. Baek committed
8
	import { getChatList, updateChatById } from '$lib/apis/chats';
9

10
11
12
	import UserMessage from './Messages/UserMessage.svelte';
	import ResponseMessage from './Messages/ResponseMessage.svelte';
	import Placeholder from './Messages/Placeholder.svelte';
Timothy J. Baek's avatar
Timothy J. Baek committed
13
	import Spinner from '../common/Spinner.svelte';
14
	import { imageGenerations } from '$lib/apis/images';
15
	import { copyToClipboard, findWordIndices } from '$lib/utils';
16
17
	import CompareMessages from './Messages/CompareMessages.svelte';
	import { stringify } from 'postcss';
18

19
20
	const i18n = getContext('i18n');

21
	export let chatId = '';
22
	export let readOnly = false;
23
	export let sendPrompt: Function;
Timothy J. Baek's avatar
Timothy J. Baek committed
24
	export let continueGeneration: Function;
25
26
	export let regenerateResponse: Function;

27
	export let user = $_user;
Timothy J. Baek's avatar
Timothy J. Baek committed
28
	export let prompt;
Timothy J. Baek's avatar
Timothy J. Baek committed
29
	export let suggestionPrompts = [];
Timothy J. Baek's avatar
Timothy J. Baek committed
30
	export let processing = '';
Timothy J. Baek's avatar
Timothy J. Baek committed
31
	export let bottomPadding = false;
32
33
34
35
	export let autoScroll;
	export let history = {};
	export let messages = [];

36
	export let selectedModels;
37
	export let selectedModelfiles = [];
38

Timothy J. Baek's avatar
Timothy J. Baek committed
39
40
41
	$: if (autoScroll && bottomPadding) {
		(async () => {
			await tick();
Timothy J. Baek's avatar
Timothy J. Baek committed
42
			scrollToBottom();
Timothy J. Baek's avatar
Timothy J. Baek committed
43
44
45
		})();
	}

Timothy J. Baek's avatar
Timothy J. Baek committed
46
47
48
49
50
	const scrollToBottom = () => {
		const element = document.getElementById('messages-container');
		element.scrollTop = element.scrollHeight;
	};

Timothy J. Baek's avatar
Timothy J. Baek committed
51
52
53
54
	const copyToClipboardWithToast = async (text) => {
		const res = await copyToClipboard(text);
		if (res) {
			toast.success($i18n.t('Copying to clipboard was successful!'));
55
56
57
		}
	};

58
59
	const confirmEditMessage = async (messageId, content) => {
		let userPrompt = content;
60
61
62
63
64
65
66
		let userMessageId = uuidv4();

		let userMessage = {
			id: userMessageId,
			parentId: history.messages[messageId].parentId,
			childrenIds: [],
			role: 'user',
Timothy J. Baek's avatar
Timothy J. Baek committed
67
			content: userPrompt,
68
69
			...(history.messages[messageId].files && { files: history.messages[messageId].files }),
			models: selectedModels.filter((m, mIdx) => selectedModels.indexOf(m) === mIdx)
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
		};

		let messageParentId = history.messages[messageId].parentId;

		if (messageParentId !== null) {
			history.messages[messageParentId].childrenIds = [
				...history.messages[messageParentId].childrenIds,
				userMessageId
			];
		}

		history.messages[userMessageId] = userMessage;
		history.currentId = userMessageId;

		await tick();
85
		await sendPrompt(userPrompt, userMessageId);
86
87
	};

Timothy J. Baek's avatar
Timothy J. Baek committed
88
	const updateChatMessages = async () => {
Timothy J. Baek's avatar
Timothy J. Baek committed
89
90
91
92
93
94
95
		await tick();
		await updateChatById(localStorage.token, chatId, {
			messages: messages,
			history: history
		});

		await chats.set(await getChatList(localStorage.token));
Timothy J. Baek's avatar
Timothy J. Baek committed
96
97
	};

Timothy J. Baek's avatar
Timothy J. Baek committed
98
99
100
101
102
103
104
	const confirmEditResponseMessage = async (messageId, content) => {
		history.messages[messageId].originalContent = history.messages[messageId].content;
		history.messages[messageId].content = content;

		await updateChatMessages();
	};

105
	const rateMessage = async (messageId, rating) => {
Timothy J. Baek's avatar
Timothy J. Baek committed
106
107
108
109
		history.messages[messageId].annotation = {
			...history.messages[messageId].annotation,
			rating: rating
		};
Timothy J. Baek's avatar
Timothy J. Baek committed
110

Timothy J. Baek's avatar
Timothy J. Baek committed
111
		await updateChatMessages();
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
	};

	const showPreviousMessage = async (message) => {
		if (message.parentId !== null) {
			let messageId =
				history.messages[message.parentId].childrenIds[
					Math.max(history.messages[message.parentId].childrenIds.indexOf(message.id) - 1, 0)
				];

			if (message.id !== messageId) {
				let messageChildrenIds = history.messages[messageId].childrenIds;

				while (messageChildrenIds.length !== 0) {
					messageId = messageChildrenIds.at(-1);
					messageChildrenIds = history.messages[messageId].childrenIds;
				}

				history.currentId = messageId;
			}
		} else {
			let childrenIds = Object.values(history.messages)
				.filter((message) => message.parentId === null)
				.map((message) => message.id);
			let messageId = childrenIds[Math.max(childrenIds.indexOf(message.id) - 1, 0)];

			if (message.id !== messageId) {
				let messageChildrenIds = history.messages[messageId].childrenIds;

				while (messageChildrenIds.length !== 0) {
					messageId = messageChildrenIds.at(-1);
					messageChildrenIds = history.messages[messageId].childrenIds;
				}

				history.currentId = messageId;
			}
		}

		await tick();

Timothy J. Baek's avatar
Timothy J. Baek committed
151
		const element = document.getElementById('messages-container');
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
152
		autoScroll = element.scrollHeight - element.scrollTop <= element.clientHeight + 50;
153
154

		setTimeout(() => {
Timothy J. Baek's avatar
Timothy J. Baek committed
155
			scrollToBottom();
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
		}, 100);
	};

	const showNextMessage = async (message) => {
		if (message.parentId !== null) {
			let messageId =
				history.messages[message.parentId].childrenIds[
					Math.min(
						history.messages[message.parentId].childrenIds.indexOf(message.id) + 1,
						history.messages[message.parentId].childrenIds.length - 1
					)
				];

			if (message.id !== messageId) {
				let messageChildrenIds = history.messages[messageId].childrenIds;

				while (messageChildrenIds.length !== 0) {
					messageId = messageChildrenIds.at(-1);
					messageChildrenIds = history.messages[messageId].childrenIds;
				}

				history.currentId = messageId;
			}
		} else {
			let childrenIds = Object.values(history.messages)
				.filter((message) => message.parentId === null)
				.map((message) => message.id);
			let messageId =
				childrenIds[Math.min(childrenIds.indexOf(message.id) + 1, childrenIds.length - 1)];

			if (message.id !== messageId) {
				let messageChildrenIds = history.messages[messageId].childrenIds;

				while (messageChildrenIds.length !== 0) {
					messageId = messageChildrenIds.at(-1);
					messageChildrenIds = history.messages[messageId].childrenIds;
				}

				history.currentId = messageId;
			}
		}

		await tick();

Timothy J. Baek's avatar
Timothy J. Baek committed
200
		const element = document.getElementById('messages-container');
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
201
		autoScroll = element.scrollHeight - element.scrollTop <= element.clientHeight + 50;
Timothy J. Baek's avatar
Timothy J. Baek committed
202

203
		setTimeout(() => {
Timothy J. Baek's avatar
Timothy J. Baek committed
204
			scrollToBottom();
205
206
		}, 100);
	};
207

Timothy J. Baek's avatar
Timothy J. Baek committed
208
	const messageDeleteHandler = async (messageId) => {
Timothy J. Baek's avatar
revert  
Timothy J. Baek committed
209
210
211
212
213
		const messageToDelete = history.messages[messageId];
		const messageParentId = messageToDelete.parentId;
		const messageChildrenIds = messageToDelete.childrenIds ?? [];
		const hasSibling = messageChildrenIds.some(
			(childId) => history.messages[childId]?.childrenIds?.length > 0
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
214
		);
Timothy J. Baek's avatar
revert  
Timothy J. Baek committed
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
		messageChildrenIds.forEach((childId) => {
			const child = history.messages[childId];
			if (child && child.childrenIds) {
				if (child.childrenIds.length === 0 && !hasSibling) {
					// if last prompt/response pair
					history.messages[messageParentId].childrenIds = [];
					history.currentId = messageParentId;
				} else {
					child.childrenIds.forEach((grandChildId) => {
						if (history.messages[grandChildId]) {
							history.messages[grandChildId].parentId = messageParentId;
							history.messages[messageParentId].childrenIds.push(grandChildId);
						}
					});
				}
			}
			// remove response
			history.messages[messageParentId].childrenIds = history.messages[
				messageParentId
			].childrenIds.filter((id) => id !== childId);
		});
		// remove prompt
		history.messages[messageParentId].childrenIds = history.messages[
			messageParentId
		].childrenIds.filter((id) => id !== messageId);
		await updateChatById(localStorage.token, chatId, {
			messages: messages,
			history: history
		});
244
	};
245
246
</script>

Timothy J. Baek's avatar
Timothy J. Baek committed
247
<div class="h-full flex mb-16">
Timothy J. Baek's avatar
Timothy J. Baek committed
248
249
250
251
252
253
	{#if messages.length == 0}
		<Placeholder
			models={selectedModels}
			modelfiles={selectedModelfiles}
			{suggestionPrompts}
			submitPrompt={async (p) => {
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
				let text = p;

				if (p.includes('{{CLIPBOARD}}')) {
					const clipboardText = await navigator.clipboard.readText().catch((err) => {
						toast.error($i18n.t('Failed to read clipboard contents'));
						return '{{CLIPBOARD}}';
					});

					text = p.replaceAll('{{CLIPBOARD}}', clipboardText);
				}

				prompt = text;

				await tick();

				const chatInputElement = document.getElementById('chat-textarea');
				if (chatInputElement) {
Timothy J. Baek's avatar
Timothy J. Baek committed
271
272
					prompt = p;

273
274
275
					chatInputElement.style.height = '';
					chatInputElement.style.height = Math.min(chatInputElement.scrollHeight, 200) + 'px';
					chatInputElement.focus();
Timothy J. Baek's avatar
Timothy J. Baek committed
276

277
278
279
280
281
282
					const words = findWordIndices(prompt);

					if (words.length > 0) {
						const word = words.at(0);
						chatInputElement.setSelectionRange(word?.startIndex, word.endIndex + 1);
					}
Timothy J. Baek's avatar
Timothy J. Baek committed
283
				}
284
285

				await tick();
Timothy J. Baek's avatar
Timothy J. Baek committed
286
287
288
			}}
		/>
	{:else}
Timothy J. Baek's avatar
Timothy J. Baek committed
289
		<div class="w-full pt-2">
Timothy J. Baek's avatar
Timothy J. Baek committed
290
291
			{#key chatId}
				{#each messages as message, messageIdx}
Timothy J. Baek's avatar
Timothy J. Baek committed
292
					<div class=" w-full {messageIdx === messages.length - 1 ? 'pb-28' : ''}">
Timothy J. Baek's avatar
Timothy J. Baek committed
293
294
295
						<div
							class="flex flex-col justify-between px-5 mb-3 {$settings?.fullScreenMode ?? null
								? 'max-w-full'
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
296
								: 'max-w-5xl'} mx-auto rounded-lg group"
Timothy J. Baek's avatar
Timothy J. Baek committed
297
298
299
300
						>
							{#if message.role === 'user'}
								<UserMessage
									on:delete={() => messageDeleteHandler(message.id)}
301
									{user}
Timothy J. Baek's avatar
Timothy J. Baek committed
302
303
304
305
306
307
308
309
310
311
312
313
314
									{readOnly}
									{message}
									isFirstMessage={messageIdx === 0}
									siblings={message.parentId !== null
										? history.messages[message.parentId]?.childrenIds ?? []
										: Object.values(history.messages)
												.filter((message) => message.parentId === null)
												.map((message) => message.id) ?? []}
									{confirmEditMessage}
									{showPreviousMessage}
									{showNextMessage}
									copyToClipboard={copyToClipboardWithToast}
								/>
315
							{:else if $mobile || (history.messages[message.parentId]?.models?.length ?? 1) === 1}
Timothy J. Baek's avatar
Timothy J. Baek committed
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
								{#key message.id}
									<ResponseMessage
										{message}
										modelfiles={selectedModelfiles}
										siblings={history.messages[message.parentId]?.childrenIds ?? []}
										isLastMessage={messageIdx + 1 === messages.length}
										{readOnly}
										{updateChatMessages}
										{confirmEditResponseMessage}
										{showPreviousMessage}
										{showNextMessage}
										{rateMessage}
										copyToClipboard={copyToClipboardWithToast}
										{continueGeneration}
										{regenerateResponse}
										on:save={async (e) => {
											console.log('save', e);

											const message = e.detail;
											history.messages[message.id] = message;
											await updateChatById(localStorage.token, chatId, {
												messages: messages,
												history: history
											});
										}}
									/>
								{/key}
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
							{:else}
								{#key message.parentId}
									<CompareMessages
										bind:history
										{messages}
										{chatId}
										parentMessage={history.messages[message.parentId]}
										{messageIdx}
										{selectedModelfiles}
										{updateChatMessages}
										{confirmEditResponseMessage}
										{rateMessage}
										copyToClipboard={copyToClipboardWithToast}
										{continueGeneration}
										{regenerateResponse}
										on:change={() => {
											const element = document.getElementById('messages-container');
											autoScroll =
												element.scrollHeight - element.scrollTop <= element.clientHeight + 50;

											setTimeout(() => {
												scrollToBottom();
											}, 100);
										}}
									/>
								{/key}
Timothy J. Baek's avatar
Timothy J. Baek committed
369
370
							{/if}
						</div>
Timothy J. Baek's avatar
Timothy J. Baek committed
371
					</div>
Timothy J. Baek's avatar
Timothy J. Baek committed
372
373
374
				{/each}

				{#if bottomPadding}
Timothy J. Baek's avatar
Timothy J. Baek committed
375
					<div class="  pb-20" />
Timothy J. Baek's avatar
Timothy J. Baek committed
376
377
378
379
380
				{/if}
			{/key}
		</div>
	{/if}
</div>