-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconversationStore.ts
More file actions
1028 lines (894 loc) · 32.5 KB
/
conversationStore.ts
File metadata and controls
1028 lines (894 loc) · 32.5 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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { create } from 'zustand'
import { conversations, whenReady } from '@/lib/yjs'
import type { Conversation, Message } from '@/types'
import { errorToast } from '@/lib/toast'
import { ConversationTitleGenerator } from '@/lib/conversation-title-generator'
import { getAgentById } from '@/stores/agentStore'
import {
encryptFields,
decryptFields,
encryptField,
MESSAGE_ENCRYPTED_FIELDS,
CONVERSATION_ENCRYPTED_FIELDS,
encryptStringArray,
decryptStringArray,
encryptAttachments,
decryptAttachments,
safeString,
} from '@/lib/crypto/content-encryption'
// ============================================================================
// Encryption Helpers
// ============================================================================
/**
* Encrypt a conversation's content fields for storage in Yjs.
* Encrypts message.content and pinnedDescription, message attachments (data + name),
* conversation.summary, conversation.title, and quickReplies.
*/
async function encryptConversationForStorage(
conv: Conversation,
): Promise<Conversation> {
const encryptedMessages = await Promise.all(
conv.messages.map(async (msg) => {
// Encrypt flat string fields (content, pinnedDescription)
const encryptedMsg = (await encryptFields(msg, [
...MESSAGE_ENCRYPTED_FIELDS,
])) as Message
// Encrypt attachment data + name
if (msg.attachments && msg.attachments.length > 0) {
encryptedMsg.attachments = await encryptAttachments(msg.attachments)
}
return encryptedMsg
}),
)
const result = { ...conv, messages: encryptedMessages as Message[] }
// Encrypt quickReplies (string array)
if (conv.quickReplies && conv.quickReplies.length > 0) {
result.quickReplies = (await encryptStringArray(
conv.quickReplies,
)) as string[]
}
// Encrypt conversation-level fields (summary, title)
return encryptFields(result, [
...CONVERSATION_ENCRYPTED_FIELDS,
]) as Promise<Conversation>
}
/**
* Decrypt a conversation's content fields after reading from Yjs.
* Handles backward compatibility: unencrypted data passes through unchanged.
*/
async function decryptConversationFromStorage(
conv: Conversation,
): Promise<Conversation> {
const decryptedMessages = await Promise.all(
conv.messages.map(async (msg) => {
// Decrypt flat string fields (content, pinnedDescription)
const decryptedMsg = (await decryptFields(msg, [
...MESSAGE_ENCRYPTED_FIELDS,
])) as Message
// Decrypt attachment data + name
if (msg.attachments && msg.attachments.length > 0) {
decryptedMsg.attachments = await decryptAttachments(msg.attachments)
}
return decryptedMsg
}),
)
const result = { ...conv, messages: decryptedMessages as Message[] }
// Decrypt quickReplies
if (conv.quickReplies && conv.quickReplies.length > 0) {
result.quickReplies = (await decryptStringArray(
conv.quickReplies as (
| string
| import('@/lib/crypto/content-encryption').EncryptedField
)[],
)) as string[]
}
// Decrypt conversation-level fields (summary, title)
return decryptFields(result, [
...CONVERSATION_ENCRYPTED_FIELDS,
]) as Promise<Conversation>
}
/**
* Lightweight decryption of conversation metadata (title, summary) for sidebar display.
* Does NOT decrypt message content or attachments — much faster for list rendering.
*/
async function decryptConversationMetadata(
conv: Conversation,
): Promise<Conversation> {
return decryptFields(conv, [
...CONVERSATION_ENCRYPTED_FIELDS,
]) as Promise<Conversation>
}
// ============================================================================
// Helper: Normalize a date value that may have been corrupted by Yjs binary
// serialization (Date objects have no enumerable properties, so Yjs encodes
// them as empty plain objects {} which survive as {} after page reload).
// ============================================================================
function normalizeYjsDate(value: unknown): string | Date {
if (value instanceof Date && !isNaN(value.getTime()))
return value.toISOString()
if (typeof value === 'string' || typeof value === 'number')
return value as string
// Yjs encoded the Date as {} — return epoch 0 (clearly invalid, but safe; avoids
// claiming this conversation was created "right now" which would corrupt backups)
return new Date(0).toISOString()
}
// ============================================================================
// Helper: Get all conversations from Yjs map
// ============================================================================
function getAllConversations(): Conversation[] {
return Array.from(conversations.values()).map((conv) => ({
...conv,
timestamp: normalizeYjsDate(conv.timestamp),
updatedAt: normalizeYjsDate(conv.updatedAt),
}))
}
// ============================================================================
// Store Interface
// ============================================================================
interface ConversationStore {
conversations: Conversation[]
currentConversation: Conversation | null
isLoading: boolean
searchQuery: string
showPinnedOnly: boolean
loadConversations: () => Promise<void>
loadConversation: (id: string) => Promise<Conversation | null>
createConversation: (
agentId: string,
workflowId: string,
) => Promise<Conversation>
addMessage: (
conversationId: string,
message: Omit<Message, 'id' | 'timestamp'>,
) => Promise<void>
addAgentToConversation: (
conversationId: string,
agentId: string,
) => Promise<void>
deleteConversation: (id: string) => Promise<void>
clearCurrentConversation: () => void
getConversationTitle: (conversation: Conversation) => string
generateAndUpdateTitle: (conversationId: string) => Promise<void>
generateTitleForMessage: (
conversationId: string,
userMessage: string,
) => Promise<void>
// Search
setSearchQuery: (query: string) => void
searchConversations: (query: string) => Conversation[]
setShowPinnedOnly: (show: boolean) => void
// Pinning conversations
pinConversation: (id: string) => Promise<void>
unpinConversation: (id: string) => Promise<void>
// Pinning messages
pinMessage: (conversationId: string, messageId: string) => Promise<void>
unpinMessage: (conversationId: string, messageId: string) => Promise<void>
// Update message
updateMessage: (
conversationId: string,
messageId: string,
content: string,
) => Promise<void>
// Summarization
summarizeConversation: (conversationId: string) => Promise<string>
// Rename conversation
renameConversation: (
conversationId: string,
newTitle: string,
) => Promise<void>
// Quick replies
updateQuickReplies: (
conversationId: string,
quickReplies: string[],
) => Promise<void>
}
export const useConversationStore = create<ConversationStore>((set, get) => {
// Subscribe to Yjs changes to keep Zustand state in sync
conversations.observe(() => {
const allConversations = getAllConversations()
const { currentConversation } = get()
// Decrypt metadata (title, summary) for sidebar display
Promise.all(
allConversations.map((conv) => decryptConversationMetadata(conv)),
).then((decryptedList) => {
set({ conversations: decryptedList })
})
// If current conversation changed in Yjs, async-decrypt and update state
if (currentConversation) {
const rawUpdated = conversations.get(currentConversation.id)
if (rawUpdated) {
decryptConversationFromStorage(rawUpdated).then((decrypted) => {
set({ currentConversation: decrypted })
})
} else {
set({ currentConversation: null })
}
}
})
return {
conversations: [],
currentConversation: null,
isLoading: false,
searchQuery: '',
showPinnedOnly: false,
loadConversations: async () => {
set({ isLoading: true })
try {
// Wait for Yjs to be ready (IndexedDB synced)
await whenReady
const allConversations = getAllConversations()
// Decrypt metadata (title, summary) for sidebar display
const decryptedList = await Promise.all(
allConversations.map((conv) => decryptConversationMetadata(conv)),
)
set({ conversations: decryptedList, isLoading: false })
} catch (error) {
errorToast('Failed to load conversations', error)
set({ isLoading: false })
}
},
loadConversation: async (id: string) => {
set({ isLoading: true })
try {
// Wait for Yjs to be ready
await whenReady
const conversation = conversations.get(id)
if (conversation) {
// Decrypt content fields from storage
const decrypted = await decryptConversationFromStorage(conversation)
// Migrate legacy conversations: backfill agentSlug if missing
if (!decrypted.agentSlug && decrypted.agentId) {
const agent = await getAgentById(decrypted.agentId)
if (agent?.slug) {
const updatedConversation = {
...decrypted,
agentSlug: agent.slug,
}
// Persist the migration to Yjs (re-encrypt)
const encrypted =
await encryptConversationForStorage(updatedConversation)
conversations.set(id, encrypted)
set({
currentConversation: updatedConversation,
isLoading: false,
})
return updatedConversation
}
}
set({ currentConversation: decrypted, isLoading: false })
return decrypted
} else {
errorToast(
'Conversation not found',
'The requested conversation could not be found',
)
set({ isLoading: false })
return null
}
} catch (error) {
errorToast('Failed to load conversations', error)
set({ isLoading: false })
return null
}
},
createConversation: async (agentId: string, workflowId: string) => {
set({ isLoading: true })
try {
// Wait for Yjs to be ready
await whenReady
// Get agent to retrieve slug
const agent = await getAgentById(agentId)
const agentSlug = agent?.slug
// Create conversation without initial system message
// The system prompt will be dynamically built and added by chat.ts when messages are sent
const now = new Date().toISOString()
const conversation: Conversation = {
id: crypto.randomUUID(),
agentId,
agentSlug,
participatingAgents: [agentId],
workflowId,
timestamp: now,
updatedAt: now,
messages: [],
}
// Write to Yjs (single source of truth)
conversations.set(conversation.id, conversation)
// Update local state
set({
currentConversation: conversation,
isLoading: false,
})
return conversation
} catch (error) {
errorToast('Failed to create conversation', error)
set({ isLoading: false })
throw error
}
},
addMessage: async (
conversationId: string,
message: Omit<Message, 'id' | 'timestamp'>,
) => {
set({ isLoading: true })
try {
// Wait for Yjs to be ready
await whenReady
const conversation = conversations.get(conversationId)
if (!conversation) {
throw new Error('Conversation not found')
}
const newMessage: Message = {
...message,
id: crypto.randomUUID(),
timestamp: new Date().toISOString(),
}
// Encrypt the new message content and pinnedDescription for Yjs storage
const encryptedMessage = (await encryptFields(newMessage, [
...MESSAGE_ENCRYPTED_FIELDS,
])) as Message
// Encrypt attachments (data + name) if present
if (newMessage.attachments && newMessage.attachments.length > 0) {
encryptedMessage.attachments = await encryptAttachments(
newMessage.attachments,
)
}
// Clone for immutability — work with the raw (encrypted) conversation from Yjs
const updatedConversation = { ...conversation }
// If this is an assistant message with an agentId, add agent to participating agents
if (message.role === 'assistant' && message.agentId) {
// Initialize participatingAgents if it doesn't exist (backward compatibility)
if (!updatedConversation.participatingAgents) {
updatedConversation.participatingAgents = [
updatedConversation.agentId,
]
}
if (
!updatedConversation.participatingAgents.includes(message.agentId)
) {
updatedConversation.participatingAgents = [
...updatedConversation.participatingAgents,
message.agentId,
]
}
}
// Add encrypted message to the array (existing messages already encrypted)
updatedConversation.messages = [
...conversation.messages,
encryptedMessage,
]
updatedConversation.updatedAt = new Date().toISOString()
// Write encrypted conversation to Yjs
conversations.set(conversationId, updatedConversation)
// For Zustand state, use the decrypted version from existing state + plaintext new message
const { currentConversation } = get()
if (currentConversation?.id === conversationId) {
const decryptedState = {
...currentConversation,
...(!currentConversation.participatingAgents
? {}
: {
participatingAgents: updatedConversation.participatingAgents,
}),
messages: [...currentConversation.messages, newMessage],
updatedAt: updatedConversation.updatedAt,
}
set({ currentConversation: decryptedState, isLoading: false })
} else {
set({ isLoading: false })
}
// Generate title if this is the first user message and no title exists
if (message.role === 'user' && !updatedConversation.title) {
const userMessagesCount = updatedConversation.messages.filter(
(m) => m.role === 'user',
).length
if (userMessagesCount === 1) {
// Generate title asynchronously without blocking the UI
get()
.generateTitleForMessage(conversationId, message.content)
.catch((error) => {
console.warn(
'Title generation failed, but message was saved:',
error,
)
})
}
}
} catch (error) {
errorToast('Failed to add message', error)
set({ isLoading: false })
}
},
deleteConversation: async (id: string) => {
set({ isLoading: true })
try {
// Wait for Yjs to be ready
await whenReady
// Delete from Yjs (hard delete for conversations)
conversations.delete(id)
const { currentConversation } = get()
set({
currentConversation:
currentConversation?.id === id ? null : currentConversation,
isLoading: false,
})
} catch (error) {
errorToast('Failed to delete conversations', error)
set({ isLoading: false })
}
},
clearCurrentConversation: () => {
set({ currentConversation: null })
},
addAgentToConversation: async (conversationId: string, agentId: string) => {
set({ isLoading: true })
try {
// Wait for Yjs to be ready
await whenReady
const conversation = conversations.get(conversationId)
if (!conversation) {
throw new Error('Conversation not found')
}
// Clone for immutability
const updatedConversation = { ...conversation }
// Initialize participatingAgents if it doesn't exist (backward compatibility)
if (!updatedConversation.participatingAgents) {
updatedConversation.participatingAgents = [
updatedConversation.agentId,
]
}
if (!updatedConversation.participatingAgents.includes(agentId)) {
updatedConversation.participatingAgents = [
...updatedConversation.participatingAgents,
agentId,
]
// Write to Yjs
conversations.set(conversationId, updatedConversation)
const { currentConversation } = get()
set({
currentConversation:
currentConversation?.id === conversationId
? updatedConversation
: currentConversation,
isLoading: false,
})
} else {
set({ isLoading: false })
}
} catch (error) {
errorToast('Failed to add agent to conversation', error)
set({ isLoading: false })
}
},
getConversationTitle: (conversation: Conversation) => {
// Use stored title if available and it is a string (not an encrypted field)
const title = safeString(conversation.title)
if (title) {
return title
}
// Fallback to first user message truncation (legacy behavior)
const firstUserMessage = conversation.messages.find(
(msg) => msg.role === 'user',
)
if (firstUserMessage && typeof firstUserMessage.content === 'string') {
// Truncate to 50 characters for title
const title = firstUserMessage.content.slice(0, 50)
return title.length < firstUserMessage.content.length
? title + '...'
: title
}
return 'New Conversation'
},
generateAndUpdateTitle: async (conversationId: string) => {
try {
const conversation = conversations.get(conversationId)
if (!conversation) {
console.warn(
'Conversation not found for title generation:',
conversationId,
)
return
}
// Generate title using LLM
const title =
await ConversationTitleGenerator.generateTitle(conversation)
// Encrypt title for Yjs storage
const encryptedTitle = await encryptField(title)
const updatedConversation = {
...conversation,
title: (encryptedTitle ?? title) as unknown as string,
}
// Write to Yjs
conversations.set(conversationId, updatedConversation)
// Update currentConversation with plaintext title
const { currentConversation } = get()
if (currentConversation?.id === conversationId) {
set({
currentConversation: { ...currentConversation, title },
})
}
} catch (error) {
console.error('Failed to generate conversation title:', error)
// Don't show error toast for title generation failures as it's not critical
}
},
generateTitleForMessage: async (
conversationId: string,
userMessage: string,
) => {
try {
// Generate title immediately from the user message
const title =
await ConversationTitleGenerator.generateTitleForNewConversation(
conversationId,
userMessage,
)
// Update conversation with generated title
const conversation = conversations.get(conversationId)
if (!conversation) {
console.warn(
'Conversation not found for title generation:',
conversationId,
)
return
}
// Encrypt title for Yjs storage
const encryptedTitle = await encryptField(title)
const updatedConversation = {
...conversation,
title: (encryptedTitle ?? title) as unknown as string,
}
// Write to Yjs
conversations.set(conversationId, updatedConversation)
// Update currentConversation with plaintext title
const { currentConversation } = get()
if (currentConversation?.id === conversationId) {
set({
currentConversation: { ...currentConversation, title },
})
}
} catch (error) {
console.error('Failed to generate title for new message:', error)
// Don't show error toast for title generation failures as it's not critical
}
},
// =========================================================================
// Search Methods
// =========================================================================
setSearchQuery: (query: string) => {
set({ searchQuery: query })
},
searchConversations: (query: string) => {
const allConversations = getAllConversations()
if (!query || query.trim() === '') {
return allConversations
}
const lowerQuery = query.toLowerCase()
return allConversations.filter((conversation) => {
// Search in title (skip if encrypted — typeof check)
if (
typeof conversation.title === 'string' &&
conversation.title.toLowerCase().includes(lowerQuery)
) {
return true
}
// Search in summary (skip if encrypted — typeof check)
if (
typeof conversation.summary === 'string' &&
conversation.summary.toLowerCase().includes(lowerQuery)
) {
return true
}
// Search in message content (skip encrypted messages — typeof check)
return conversation.messages.some(
(message) =>
typeof message.content === 'string' &&
message.content.toLowerCase().includes(lowerQuery),
)
})
},
setShowPinnedOnly: (show: boolean) => {
set({ showPinnedOnly: show })
},
// =========================================================================
// Pinning Conversations
// =========================================================================
pinConversation: async (id: string) => {
try {
await whenReady
const conversation = conversations.get(id)
if (!conversation) {
throw new Error('Conversation not found')
}
const updatedConversation = {
...conversation,
isPinned: true,
}
// Write to Yjs
conversations.set(id, updatedConversation)
const { currentConversation } = get()
if (currentConversation?.id === id) {
set({ currentConversation: updatedConversation })
}
} catch (error) {
errorToast('Failed to pin conversation', error)
}
},
unpinConversation: async (id: string) => {
try {
await whenReady
const conversation = conversations.get(id)
if (!conversation) {
throw new Error('Conversation not found')
}
const updatedConversation = {
...conversation,
isPinned: false,
}
// Write to Yjs
conversations.set(id, updatedConversation)
const { currentConversation } = get()
if (currentConversation?.id === id) {
set({ currentConversation: updatedConversation })
}
} catch (error) {
errorToast('Failed to unpin conversation', error)
}
},
// =========================================================================
// Pinning Messages
// =========================================================================
pinMessage: async (conversationId: string, messageId: string) => {
try {
await whenReady
const conversation = conversations.get(conversationId)
if (!conversation) {
throw new Error('Conversation not found')
}
// Find the message index
const messageIndex = conversation.messages.findIndex(
(m) => m.id === messageId,
)
if (messageIndex === -1) {
throw new Error('Message not found')
}
// Clone conversation and messages for immutability
const updatedMessages = [...conversation.messages]
updatedMessages[messageIndex] = {
...updatedMessages[messageIndex],
isPinned: true,
pinnedAt: new Date().toISOString(),
}
// Add to pinnedMessageIds array if not present
const pinnedMessageIds = conversation.pinnedMessageIds
? [...conversation.pinnedMessageIds]
: []
if (!pinnedMessageIds.includes(messageId)) {
pinnedMessageIds.push(messageId)
}
const updatedConversation = {
...conversation,
messages: updatedMessages,
pinnedMessageIds,
updatedAt: new Date().toISOString(),
}
// Write to Yjs
conversations.set(conversationId, updatedConversation)
const { currentConversation } = get()
if (currentConversation?.id === conversationId) {
set({ currentConversation: updatedConversation })
}
} catch (error) {
errorToast('Failed to pin message', error)
}
},
unpinMessage: async (conversationId: string, messageId: string) => {
try {
await whenReady
const conversation = conversations.get(conversationId)
if (!conversation) {
throw new Error('Conversation not found')
}
// Find the message index
const messageIndex = conversation.messages.findIndex(
(m) => m.id === messageId,
)
if (messageIndex === -1) {
throw new Error('Message not found')
}
// Clone conversation and messages for immutability
const updatedMessages = [...conversation.messages]
updatedMessages[messageIndex] = {
...updatedMessages[messageIndex],
isPinned: false,
pinnedAt: undefined,
pinnedDescription: undefined,
}
// Remove from pinnedMessageIds array
const pinnedMessageIds = conversation.pinnedMessageIds
? conversation.pinnedMessageIds.filter((id) => id !== messageId)
: []
const updatedConversation = {
...conversation,
messages: updatedMessages,
pinnedMessageIds,
updatedAt: new Date().toISOString(),
}
// Write to Yjs
conversations.set(conversationId, updatedConversation)
const { currentConversation } = get()
if (currentConversation?.id === conversationId) {
set({ currentConversation: updatedConversation })
}
} catch (error) {
errorToast('Failed to unpin message', error)
}
},
// =========================================================================
// Update Message
// =========================================================================
updateMessage: async (
conversationId: string,
messageId: string,
content: string,
) => {
try {
await whenReady
const conversation = conversations.get(conversationId)
if (!conversation) {
throw new Error('Conversation not found')
}
// Find the message index
const messageIndex = conversation.messages.findIndex(
(m) => m.id === messageId,
)
if (messageIndex === -1) {
throw new Error('Message not found')
}
// Encrypt the new content for Yjs storage
const encryptedContent = await encryptField(content)
// Clone conversation and messages — update with encrypted content for Yjs
const updatedMessages = [...conversation.messages]
updatedMessages[messageIndex] = {
...updatedMessages[messageIndex],
content: (encryptedContent ?? content) as unknown as string,
}
const updatedConversation = {
...conversation,
messages: updatedMessages,
updatedAt: new Date().toISOString(),
}
// Write encrypted to Yjs
conversations.set(conversationId, updatedConversation)
// For Zustand state, use plaintext content
const { currentConversation } = get()
if (currentConversation?.id === conversationId) {
const stateMessages = [...currentConversation.messages]
if (messageIndex < stateMessages.length) {
stateMessages[messageIndex] = {
...stateMessages[messageIndex],
content,
}
}
set({
currentConversation: {
...currentConversation,
messages: stateMessages,
updatedAt: updatedConversation.updatedAt,
},
})
}
} catch (error) {
errorToast('Failed to update message', error)
}
},
// =========================================================================
// Summarization
// =========================================================================
summarizeConversation: async (conversationId: string) => {
try {
await whenReady
const conversation = conversations.get(conversationId)
if (!conversation) {
throw new Error('Conversation not found')
}
// Decrypt conversation for the summarizer to work with plaintext
const decrypted = await decryptConversationFromStorage(conversation)
// Dynamically import the summarizer to avoid circular dependencies
const { ConversationSummarizer } = await import(
'@/lib/conversation-summarizer'
)
const summary =
await ConversationSummarizer.summarizeConversation(decrypted)
// Encrypt the summary for Yjs storage
const encryptedSummary = await encryptField(summary)
// Update conversation with encrypted summary in Yjs
const updatedConversation = {
...conversation,
summary: (encryptedSummary ?? summary) as unknown as string,
updatedAt: new Date().toISOString(),
}
// Write encrypted to Yjs
conversations.set(conversationId, updatedConversation)
// For Zustand state, use plaintext summary
const { currentConversation } = get()
if (currentConversation?.id === conversationId) {
set({
currentConversation: {
...currentConversation,
summary,
updatedAt: updatedConversation.updatedAt,
},
})
}
return summary
} catch (error) {
errorToast('Failed to summarize conversation', error)
throw error
}
},
// =========================================================================
// Rename conversation
// =========================================================================
renameConversation: async (conversationId: string, newTitle: string) => {
try {
await whenReady
const conversation = conversations.get(conversationId)
if (!conversation) {
throw new Error('Conversation not found')
}
const trimmedTitle = newTitle.trim()
// Encrypt title for Yjs storage
const encryptedTitle = await encryptField(trimmedTitle)
const updatedConversation = {
...conversation,
title: (encryptedTitle ?? trimmedTitle) as unknown as string,
updatedAt: new Date().toISOString(),
}
// Write to Yjs
conversations.set(conversationId, updatedConversation)
// For Zustand state, use plaintext title
const { currentConversation } = get()
if (currentConversation?.id === conversationId) {
set({
currentConversation: {
...currentConversation,
title: trimmedTitle,
updatedAt: updatedConversation.updatedAt,
},
})
}
} catch (error) {
errorToast('Failed to rename conversation', error)
throw error
}
},
updateQuickReplies: async (
conversationId: string,
quickReplies: string[],
) => {
const conversation = conversations.get(conversationId)