-
-
Notifications
You must be signed in to change notification settings - Fork 443
Expand file tree
/
Copy pathConversations.py
More file actions
4719 lines (4313 loc) · 177 KB
/
Conversations.py
File metadata and controls
4719 lines (4313 loc) · 177 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
from datetime import datetime, timedelta
import logging
import secrets
import asyncio
import pytz
import re
import base64
import hashlib
import os
import uuid
from DB import (
Conversation,
ConversationShare,
ConversationParticipant,
Agent,
Message,
MessageReaction,
DiscardedContext,
Memory,
User,
UserCompany,
get_session,
)
from Globals import getenv, DEFAULT_USER
from sqlalchemy.sql import func, or_, and_, case, exists
from MagicalAuth import convert_time, get_user_id, get_user_timezone
from SharedCache import shared_cache
logging.basicConfig(
level=getenv("LOG_LEVEL"),
format=getenv("LOG_FORMAT"),
)
# Cache TTL for conversation ID lookups (uses SharedCache)
_conversation_id_cache_ttl = 30 # 30 seconds
def _find_markdown_data_urls(message: str):
"""
Find all markdown data URL references in a message using imperative O(n)
parsing. Returns list of (start, end, is_image, alt_text, data_url) tuples.
This avoids regex backtracking entirely — Python's re module does not
optimize [^\\]]*\\] patterns, causing O(n²) on strings with many '[' but
no ']' (CodeQL: polynomial regular expression).
"""
results = []
pos = 0
msg_len = len(message)
while pos < msg_len:
# Find the next '[' character
bracket_start = message.find("[", pos)
if bracket_start == -1:
break
# Check for '!' prefix (image syntax)
is_image = bracket_start > 0 and message[bracket_start - 1] == "!"
match_start = bracket_start - 1 if is_image else bracket_start
# Find the closing ']'
bracket_end = message.find("]", bracket_start + 1)
if bracket_end == -1:
break # No more ']' in the string, stop scanning
# Check for '(' immediately after ']'
if bracket_end + 1 >= msg_len or message[bracket_end + 1] != "(":
pos = bracket_end + 1
continue
# Check if the URL starts with 'data:'
url_start = bracket_end + 2
if not message[url_start : url_start + 5] == "data:":
pos = bracket_end + 1
continue
# Find the closing ')'
paren_end = message.find(")", url_start)
if paren_end == -1:
break # No more ')' in the string, stop scanning
alt_text = message[bracket_start + 1 : bracket_end]
data_url = message[url_start:paren_end]
results.append((match_start, paren_end + 1, is_image, alt_text, data_url))
pos = paren_end + 1
return results
# Minimum size threshold for extracting data URLs to workspace (10KB)
# Smaller data URLs (like tiny icons) are left inline
_DATA_URL_SIZE_THRESHOLD = 10 * 1024
# MIME type to file extension mapping
_MIME_TO_EXT = {
"image/png": ".png",
"image/jpeg": ".jpg",
"image/gif": ".gif",
"image/webp": ".webp",
"image/svg+xml": ".svg",
"image/bmp": ".bmp",
"video/mp4": ".mp4",
"video/webm": ".webm",
"video/ogg": ".ogv",
"audio/webm": ".webm",
"audio/wav": ".wav",
"audio/mpeg": ".mp3",
"audio/mp3": ".mp3",
"audio/ogg": ".ogg",
"audio/flac": ".flac",
"audio/m4a": ".m4a",
"audio/aac": ".aac",
"application/pdf": ".pdf",
"application/octet-stream": ".bin",
}
def _safe_join_path(base_dir: str, *parts: str) -> str:
"""Join path components and verify the result stays under *base_dir*.
Uses ``os.path.realpath`` + ``str.startswith`` so static-analysis
tools (CodeQL ``py/path-injection``) recognise the guard as a
path-traversal sanitizer.
Raises ``ValueError`` if the resolved path escapes *base_dir*.
"""
resolved_base = os.path.realpath(base_dir)
resolved = os.path.realpath(os.path.join(base_dir, *parts))
# startswith(base + sep) handles the "base_dir_extra" false-positive;
# the equality check covers the edge case where resolved == base.
if not (resolved.startswith(resolved_base + os.sep) or resolved == resolved_base):
raise ValueError(
f"Path escapes base directory: {resolved!r} is not under {resolved_base!r}"
)
return resolved
def _sanitize_filename(name: str, default_ext: str) -> str:
"""
Sanitize a user-controlled filename so it is safe to use on disk.
Strips directory components, rejects traversal tokens, and falls
back to a random name when invalid.
"""
base = os.path.basename(str(name).strip())
if not base or base in (".", "..") or os.path.isabs(base):
return f"{uuid.uuid4().hex[:12]}{default_ext}"
if "/" in base or "\\" in base or ".." in base:
return f"{uuid.uuid4().hex[:12]}{default_ext}"
return base
def extract_data_urls_to_workspace(
message: str, agent_id: str, conversation_id: str
) -> str:
"""
Extract base64 data URLs from markdown message content and save them as
workspace files. Returns the message with data URLs replaced by /outputs/ URLs.
This prevents massive base64 strings from being stored in the database and
rendered in the DOM, which causes performance issues especially for video/audio.
Args:
message: The message content potentially containing base64 data URLs
agent_id: The agent ID for workspace path
conversation_id: The conversation ID for workspace path
Returns:
The message with base64 data URLs replaced by /outputs/ URLs
"""
if not message or "data:" not in message or "base64," not in message:
return message
agixt_uri = getenv("AGIXT_URI")
# Use os.getcwd()/WORKSPACE to match the Workspace manager's path
# (not WORKING_DIRECTORY env which may point to a different location)
working_directory = os.path.join(os.getcwd(), "WORKSPACE")
# Hash agent_id to match workspace directory pattern
agent_hash = hashlib.sha256(str(agent_id).encode()).hexdigest()[:16]
agent_folder = f"agent_{agent_hash}"
def _process_data_url(is_image, alt_text, data_url):
"""Process a single data URL match and return the replacement string."""
try:
# Parse MIME type and base64 payload from the data URL
if ";base64," not in data_url:
return None
mime_part, base64_data = data_url.split(";base64,", 1)
mime_type = mime_part[5:] # Strip "data:" prefix
base64_data = base64_data.strip()
# Validate base64 data contains only valid characters
if not base64_data or not re.fullmatch(r"[A-Za-z0-9+/=\s]+", base64_data):
return None
# Check size threshold - only extract large data URLs
data_size = len(base64_data) * 3 // 4 # Approximate decoded size
if data_size < _DATA_URL_SIZE_THRESHOLD:
return None # Leave small data URLs inline
# Decode the base64 data
file_data = base64.b64decode(base64_data)
# Strip MIME type parameters for extension lookup
# e.g., "audio/webm;codecs=opus" -> "audio/webm"
base_mime = mime_type.split(";")[0].strip()
# Determine file extension from MIME type
ext = _MIME_TO_EXT.get(base_mime, "")
if not ext:
# Try to extract from base MIME type
parts = base_mime.split("/")
if len(parts) == 2:
ext = f".{parts[1]}"
else:
ext = ".bin"
# Use alt text as filename if it has an extension, otherwise generate one
if alt_text and "." in alt_text:
filename = _sanitize_filename(alt_text, ext)
else:
filename = _sanitize_filename(f"{uuid.uuid4().hex[:12]}{ext}", ext)
# Build the workspace file path
# Sanitize conversation_id to prevent path traversal
safe_conv_id = os.path.basename(str(conversation_id))
if not safe_conv_id or safe_conv_id in (".", ".."):
safe_conv_id = "unknown_conversation"
if os.path.isabs(safe_conv_id) or ".." in safe_conv_id:
logging.warning(
"Rejected unsafe conversation_id for workspace path; "
"falling back to generated directory name."
)
safe_conv_id = uuid.uuid4().hex[:12]
workspace_root = os.path.realpath(
os.path.join(working_directory, agent_folder)
)
# _safe_join_path uses realpath+startswith (CodeQL-recognised
# sanitizer) so the taint chain is broken for downstream uses.
try:
workspace_dir = _safe_join_path(workspace_root, safe_conv_id)
except ValueError:
logging.warning(
"Rejected unsafe workspace_dir; falling back to generated directory name."
)
workspace_dir = _safe_join_path(workspace_root, uuid.uuid4().hex[:12])
os.makedirs(workspace_dir, exist_ok=True)
# Construct the final file path with fully sanitized filename
filename = _sanitize_filename(filename, ext)
try:
file_path = _safe_join_path(workspace_dir, filename)
except ValueError:
filename = _sanitize_filename(f"{uuid.uuid4().hex[:12]}{ext}", ext)
file_path = _safe_join_path(workspace_dir, filename)
# Handle filename collisions (e.g., multiple "recording.webm" files)
if os.path.exists(file_path):
name_part, ext_part = os.path.splitext(filename)
filename = _sanitize_filename(
f"{name_part}_{uuid.uuid4().hex[:8]}{ext_part}",
ext_part or ext,
)
try:
file_path = _safe_join_path(workspace_dir, filename)
except ValueError:
filename = _sanitize_filename(f"{uuid.uuid4().hex[:12]}{ext}", ext)
file_path = _safe_join_path(workspace_dir, filename)
# Write the file
with open(file_path, "wb") as f:
f.write(file_data)
# Build the /outputs/ URL
# Use the raw agent_id (not the hashed folder name) because
# the serve_file endpoint hashes agent_id via _get_local_cache_path
output_url = f"{agixt_uri}/outputs/{agent_id}/{conversation_id}/{filename}"
# Determine if it should be an image (!) or link markdown
if is_image:
return f""
else:
return f"[{alt_text}]({output_url})"
except Exception as e:
logging.warning(f"Failed to extract data URL to workspace: {e}")
return None # Return None to keep original on failure
# Use imperative O(n) parser instead of regex to avoid polynomial
# backtracking (CodeQL: polynomial regular expression on uncontrolled data)
matches = _find_markdown_data_urls(message)
if not matches:
return message
# Build result by splicing original string with replacements
parts = []
last_end = 0
for start, end, is_img, alt, data_url in matches:
replacement = _process_data_url(is_img, alt, data_url)
if replacement is not None:
parts.append(message[last_end:start])
parts.append(replacement)
last_end = end
parts.append(message[last_end:])
return "".join(parts)
def _get_conversation_cache_key(conversation_name: str, user_id: str) -> str:
return f"conversation_id:{user_id}:{conversation_name}"
def invalidate_conversation_cache(user_id: str = None, conversation_name: str = None):
"""Invalidate conversation cache entries (uses SharedCache)."""
if user_id is None:
shared_cache.delete_pattern("conversation_id:*")
elif conversation_name:
cache_key = _get_conversation_cache_key(conversation_name, str(user_id))
shared_cache.delete(cache_key)
else:
# Invalidate all entries for this user
shared_cache.delete_pattern(f"conversation_id:{user_id}:*")
async def broadcast_message_to_conversation(
conversation_id: str, event_type: str, message_data: dict
) -> int:
"""
Broadcast a message event to all WebSocket listeners for a conversation.
This is an async function that should be called from extensions that want to
send real-time updates to connected WebSocket clients.
Args:
conversation_id: The conversation ID to broadcast to
event_type: Either 'message_added' or 'message_updated'
message_data: The message data to send (should include id, role, message, etc.)
Returns:
Number of WebSocket connections that received the broadcast
"""
try:
# Import here to avoid circular imports
from endpoints.Conversation import conversation_message_broadcaster
return await conversation_message_broadcaster.broadcast_message_event(
conversation_id, event_type, message_data
)
except Exception as e:
logging.warning(
f"Failed to broadcast message to conversation {conversation_id}: {e}"
)
return 0
def broadcast_message_sync(conversation_id: str, event_type: str, message_data: dict):
"""
Synchronous wrapper for broadcast_message_to_conversation.
Use this from synchronous code (like extensions) to broadcast messages.
Uses Redis pub/sub for cross-worker distribution when available.
"""
logging.debug(
f"broadcast_message_sync called: conv={conversation_id}, type={event_type}, msg_id={message_data.get('id')}"
)
try:
# Import broadcaster to use Redis pub/sub
from endpoints.Conversation import conversation_message_broadcaster
# Try Redis pub/sub first - this is synchronous and works from any thread
if conversation_message_broadcaster.publish_to_redis(
conversation_id, event_type, message_data
):
logging.debug(f"broadcast_message_sync: published to Redis")
return
# Fallback to main event loop scheduling if Redis not available
main_loop = conversation_message_broadcaster.get_main_loop()
if main_loop is not None:
# Use the broadcaster's main event loop for cross-thread safety
future = asyncio.run_coroutine_threadsafe(
broadcast_message_to_conversation(
conversation_id, event_type, message_data
),
main_loop,
)
# Don't wait - fire and forget for streaming performance
logging.debug(
f"broadcast_message_sync: scheduled on main loop (loop={id(main_loop)})"
)
else:
logging.warning(f"broadcast_message_sync: main loop not available yet")
except Exception as e:
logging.warning(f"broadcast_message_sync error: {e}")
def get_conversation_id_by_name(conversation_name, user_id, create_if_missing=True):
"""Get the conversation ID by name, optionally creating it if it doesn't exist.
Args:
conversation_name: The name of the conversation
user_id: The user ID who owns the conversation
create_if_missing: If True (default), creates the conversation if it doesn't exist.
If False, returns None when conversation doesn't exist.
"""
user_id = str(user_id)
cache_key = _get_conversation_cache_key(conversation_name, user_id)
# Only use cache when create_if_missing=True, because cached IDs might reference
# deleted conversations and we need to verify existence when not creating
if create_if_missing:
cached = shared_cache.get(cache_key)
if cached is not None:
return cached
session = get_session()
user = session.query(User).filter(User.id == user_id).first()
conversation = (
session.query(Conversation)
.filter(
Conversation.name == conversation_name,
Conversation.user_id == user_id,
)
.first()
)
if not conversation:
# Check group conversations accessible via company membership
user_company_ids = (
session.query(UserCompany.company_id)
.filter(UserCompany.user_id == user_id)
.all()
)
company_ids = [str(uc[0]) for uc in user_company_ids]
if company_ids:
conversation = (
session.query(Conversation)
.filter(
Conversation.name == conversation_name,
Conversation.company_id.in_(company_ids),
Conversation.conversation_type.in_(
["group", "dm", "thread", "channel"]
),
)
.first()
)
if not conversation:
if not create_if_missing:
session.close()
# Clear any stale cache entry
shared_cache.delete(cache_key)
return None
# Create conversation directly to avoid recursive call to Conversations.__init__
conversation = Conversation(name=conversation_name, user_id=user_id)
session.add(conversation)
session.commit()
conversation_id = str(conversation.id)
else:
conversation_id = str(conversation.id)
session.close()
# Cache the result in SharedCache
shared_cache.set(cache_key, conversation_id, ttl=_conversation_id_cache_ttl)
return conversation_id
def get_conversation_name_by_id(conversation_id, user_id):
if conversation_id == "-":
conversation_id = get_conversation_id_by_name("-", user_id)
return "-"
session = get_session()
# First try: user's own conversation
conversation = (
session.query(Conversation)
.filter(
Conversation.id == conversation_id,
Conversation.user_id == user_id,
)
.first()
)
if not conversation:
# Second try: group conversations accessible via company membership
user_company_ids = (
session.query(UserCompany.company_id)
.filter(UserCompany.user_id == user_id)
.all()
)
company_ids = [str(uc[0]) for uc in user_company_ids]
if company_ids:
conversation = (
session.query(Conversation)
.filter(
Conversation.id == conversation_id,
Conversation.company_id.in_(company_ids),
Conversation.conversation_type.in_(
["group", "dm", "thread", "channel"]
),
)
.first()
)
if not conversation:
# Third try: conversations where user is a participant (handles DMs without company_id)
participant_conv = (
session.query(ConversationParticipant)
.filter(
ConversationParticipant.conversation_id == conversation_id,
ConversationParticipant.user_id == user_id,
ConversationParticipant.participant_type == "user",
ConversationParticipant.status == "active",
)
.first()
)
if participant_conv:
conversation = (
session.query(Conversation)
.filter(Conversation.id == conversation_id)
.first()
)
if not conversation:
session.close()
return "-"
conversation_name = conversation.name
session.close()
return conversation_name
def get_conversation_name_by_message_id(message_id, user_id):
"""Get the conversation name that contains a specific message for a user."""
session = get_session()
message = (
session.query(Message)
.join(Conversation, Message.conversation_id == Conversation.id)
.filter(
Message.id == message_id,
Conversation.user_id == user_id,
)
.first()
)
if not message:
session.close()
return None
conversation = (
session.query(Conversation)
.filter(Conversation.id == message.conversation_id)
.first()
)
conversation_name = conversation.name if conversation else None
session.close()
return conversation_name
class Conversations:
def __init__(
self,
conversation_name=None,
user=DEFAULT_USER,
conversation_id=None,
create_if_missing=True,
):
self.user = user
self.conversation_id = conversation_id
self.conversation_name = conversation_name
# Cache user_id for this instance to avoid repeated DB lookups
# get_user_id already uses SharedCache for cross-worker consistency
self._user_id = get_user_id(user)
# Resolve missing ID or name from the other
user_id = self._user_id
if not self.conversation_id and self.conversation_name:
self.conversation_id = get_conversation_id_by_name(
conversation_name=conversation_name,
user_id=user_id,
create_if_missing=create_if_missing,
)
elif not self.conversation_name and self.conversation_id:
self.conversation_name = get_conversation_name_by_id(
conversation_id=conversation_id, user_id=user_id
)
elif not self.conversation_name and not self.conversation_id:
self.conversation_name = "-"
self.conversation_id = get_conversation_id_by_name(
conversation_name="-", user_id=user_id
)
def get_current_name_from_db(self):
"""
Get the current conversation name directly from the database.
This is useful for detecting renames that happened since the object was created.
Returns:
str: The current name from the database, or None if not found
"""
if not self.conversation_id:
return self.conversation_name
session = get_session()
try:
user_id = self._user_id
if not user_id:
return self.conversation_name
conversation = (
session.query(Conversation)
.filter(
Conversation.id == self.conversation_id,
Conversation.user_id == user_id,
)
.first()
)
if conversation:
return conversation.name
return self.conversation_name
finally:
session.close()
def export_conversation(self):
session = get_session()
user_id = self._user_id
if not self.conversation_name:
self.conversation_name = "-"
conversation = (
session.query(Conversation)
.filter(
Conversation.name == self.conversation_name,
Conversation.user_id == user_id,
)
.first()
)
history = {"interactions": []}
if not conversation:
return history
messages = (
session.query(Message)
.filter(Message.conversation_id == conversation.id)
.all()
)
for message in messages:
interaction = {
"role": message.role,
"message": message.content,
"timestamp": message.timestamp,
}
history["interactions"].append(interaction)
session.close()
return history
def get_conversations(self):
session = get_session()
user_id = self._user_id
# Use a LEFT OUTER JOIN to get conversations and their messages
conversations = (
session.query(Conversation)
.outerjoin(Message, Message.conversation_id == Conversation.id)
.filter(Conversation.user_id == user_id)
.filter(Message.id != None) # Only get conversations with messages
.order_by(Conversation.updated_at.desc())
.distinct()
.all()
)
conversation_list = [conversation.name for conversation in conversations]
session.close()
return conversation_list
def get_conversations_with_ids(self):
session = get_session()
user_id = self._user_id
# Use a LEFT OUTER JOIN to get conversations and their messages
conversations = (
session.query(Conversation)
.outerjoin(Message, Message.conversation_id == Conversation.id)
.filter(Conversation.user_id == user_id)
.filter(Message.id != None) # Only get conversations with messages
.order_by(Conversation.updated_at.desc())
.distinct()
.all()
)
result = {
str(conversation.id): conversation.name for conversation in conversations
}
session.close()
return result
def get_agent_id(self, user_id):
session = get_session()
agent_name = self.get_last_agent_name()
# Get the agent's ID from the database
# Make sure this agent belongs the the right user
agent = (
session.query(Agent)
.filter(Agent.name == agent_name, Agent.user_id == user_id)
.first()
)
try:
agent_id = str(agent.id)
except:
agent_id = None
if not agent_id:
# Get the default agent for this user
agent = session.query(Agent).filter(Agent.user_id == user_id).first()
try:
agent_id = str(agent.id)
except:
agent_id = None
session.close()
return agent_id
def get_conversations_with_detail(self):
"""
OPTIMIZED: Single query to get all conversation details with notifications
and last message timestamps in one batch instead of N+1 queries.
Also includes DM conversations where the user is a participant (not just owner).
"""
session = get_session()
user_id = self._user_id
if not user_id:
session.close()
return {}
# Get default agent_id once (not per conversation - they all share the same user)
default_agent = session.query(Agent).filter(Agent.user_id == user_id).first()
default_agent_id = str(default_agent.id) if default_agent else None
# Subquery to get max message timestamp per conversation
last_message_subq = (
session.query(
Message.conversation_id,
func.max(Message.timestamp).label("last_message_time"),
)
.group_by(Message.conversation_id)
.subquery()
)
# Get conversation IDs where this user is a participant (for DMs they didn't create)
participant_conv_ids = (
session.query(ConversationParticipant.conversation_id)
.filter(
ConversationParticipant.user_id == user_id,
ConversationParticipant.participant_type == "user",
ConversationParticipant.status == "active",
)
.all()
)
participant_conv_id_list = [str(row[0]) for row in participant_conv_ids]
# Single query: conversations owned by user OR where user is a participant
# Exclude group channels and threads from DM/conversation list
ownership_filter = Conversation.user_id == user_id
participant_filter = (
Conversation.id.in_(participant_conv_id_list)
if participant_conv_id_list
else False
)
# Main query: non-group, non-thread conversations
main_conversations = (
session.query(
Conversation,
last_message_subq.c.last_message_time,
)
.outerjoin(
last_message_subq,
last_message_subq.c.conversation_id == Conversation.id,
)
.filter(or_(ownership_filter, participant_filter))
# Exclude group channels and threads from DM/conversation list
.filter(
or_(
Conversation.conversation_type.is_(None),
Conversation.conversation_type.notin_(["group", "thread"]),
)
)
# Only include conversations that have at least one message
.filter(exists().where(Message.conversation_id == Conversation.id))
.all()
)
# Second query: DM/private threads (threads whose parent is a non-group conversation)
# Get IDs of the user's DM/private conversations to find their threads
dm_parent_ids = [
str(c.id)
for c, _ in main_conversations
if c.conversation_type in (None, "dm", "private")
]
dm_threads = []
if dm_parent_ids:
dm_threads = (
session.query(
Conversation,
last_message_subq.c.last_message_time,
)
.outerjoin(
last_message_subq,
last_message_subq.c.conversation_id == Conversation.id,
)
.filter(
Conversation.conversation_type == "thread",
Conversation.parent_id.in_(dm_parent_ids),
)
.all()
)
conversations = main_conversations + dm_threads
# Batch-fetch participant records for this user to get last_read_at
all_conv_ids = [str(c.id) for c, _ in conversations]
participant_map = {}
if all_conv_ids:
user_participants = (
session.query(ConversationParticipant)
.filter(
ConversationParticipant.conversation_id.in_(all_conv_ids),
ConversationParticipant.user_id == user_id,
ConversationParticipant.participant_type == "user",
ConversationParticipant.status == "active",
)
.all()
)
for p in user_participants:
participant_map[str(p.conversation_id)] = p
# Build result dict with all data from single query
# For DM conversations, look up participant names so the frontend
# can display "DM with <name>" instead of the raw conversation name.
dm_conv_ids = [
str(c.id) for c, _ in conversations if c.conversation_type == "dm"
]
dm_participants = {}
if dm_conv_ids:
parts = (
session.query(ConversationParticipant)
.filter(
ConversationParticipant.conversation_id.in_(dm_conv_ids),
ConversationParticipant.status == "active",
)
.all()
)
# Group participants by conversation_id
for p in parts:
cid = str(p.conversation_id)
dm_participants.setdefault(cid, []).append(p)
# Batch load user/agent names for DM participants
dm_user_ids = set()
dm_agent_ids = set()
for plist in dm_participants.values():
for p in plist:
if p.participant_type == "user" and p.user_id:
dm_user_ids.add(str(p.user_id))
elif p.participant_type == "agent" and p.agent_id:
dm_agent_ids.add(str(p.agent_id))
user_name_map = {}
if dm_user_ids:
users = session.query(User).filter(User.id.in_(list(dm_user_ids))).all()
for u in users:
name = f"{u.first_name or ''} {u.last_name or ''}".strip() or u.email
user_name_map[str(u.id)] = name
agent_name_map = {}
if dm_agent_ids:
agents = session.query(Agent).filter(Agent.id.in_(list(dm_agent_ids))).all()
for a in agents:
agent_name_map[str(a.id)] = a.name
# Batch-fetch the first agent role for each conversation to identify
# which agent the conversation is with (for frontend sorting).
# Uses a window function to efficiently get the first non-USER message per conv.
conv_agent_role_map = {}
private_conv_ids = [
str(c.id)
for c, _ in conversations
if c.conversation_type is None or c.conversation_type in ("private", "dm")
]
if private_conv_ids:
# Get first non-USER, non-ACTIVITY message role per conversation
# Use a subquery to find the earliest timestamp per conversation,
# then join back to get only those rows (avoids loading ALL messages).
min_ts_subq = (
session.query(
Message.conversation_id,
func.min(Message.timestamp).label("min_ts"),
)
.filter(
Message.conversation_id.in_(private_conv_ids),
Message.role != "USER",
~Message.content.like("[ACTIVITY]%"),
~Message.content.like("[SUBACTIVITY]%"),
)
.group_by(Message.conversation_id)
.subquery()
)
first_agent_msgs = (
session.query(
Message.conversation_id,
Message.role,
)
.join(
min_ts_subq,
and_(
Message.conversation_id == min_ts_subq.c.conversation_id,
Message.timestamp == min_ts_subq.c.min_ts,
),
)
.filter(
Message.role != "USER",
~Message.content.like("[ACTIVITY]%"),
~Message.content.like("[SUBACTIVITY]%"),
)
.all()
)
for conv_id_val, role in first_agent_msgs:
cid = str(conv_id_val)
if cid not in conv_agent_role_map:
conv_agent_role_map[cid] = role
# --- Batch unread counts (replaces N+1 per-conversation COUNT queries) ---
unread_count_map = {} # conv_id -> bool (has unread)
dm_conv_id_set = set(dm_conv_ids)
# Build per-conversation baselines from participant data
with_baseline_dm = {} # conv_id -> baseline datetime (DM conversations)
with_baseline_other = {} # conv_id -> baseline datetime (non-DM conversations)
no_participant_ids = [] # conversations with no participant record
for conv_id_str in all_conv_ids:
participant = participant_map.get(conv_id_str)
if participant:
baseline = participant.last_read_at or participant.joined_at
if baseline:
if conv_id_str in dm_conv_id_set:
with_baseline_dm[conv_id_str] = baseline
else:
with_baseline_other[conv_id_str] = baseline
# else: participant exists but no baseline -> 0 unread
else:
no_participant_ids.append(conv_id_str)
# Batch query 1: DM conversations with baselines
# Count messages from OTHER users after the baseline
if with_baseline_dm:
baseline_case = case(
*[
(Message.conversation_id == cid, ts)
for cid, ts in with_baseline_dm.items()
],
)
rows = (
session.query(
Message.conversation_id,
func.count().label("cnt"),
)
.filter(
Message.conversation_id.in_(list(with_baseline_dm.keys())),
Message.timestamp > baseline_case,
~Message.content.like("[ACTIVITY]%"),
~Message.content.like("[SUBACTIVITY]%"),
or_(
Message.sender_user_id != str(user_id),
Message.role != "USER",
),
)
.group_by(Message.conversation_id)
.all()
)
for row in rows:
unread_count_map[str(row.conversation_id)] = row.cnt > 0
# Batch query 2: Non-DM conversations with baselines
# Count non-USER messages after the baseline
if with_baseline_other:
baseline_case = case(
*[
(Message.conversation_id == cid, ts)
for cid, ts in with_baseline_other.items()
],
)
rows = (
session.query(
Message.conversation_id,
func.count().label("cnt"),
)
.filter(
Message.conversation_id.in_(list(with_baseline_other.keys())),
Message.timestamp > baseline_case,
~Message.content.like("[ACTIVITY]%"),
~Message.content.like("[SUBACTIVITY]%"),
Message.role != "USER",
)
.group_by(Message.conversation_id)
.all()
)
for row in rows:
unread_count_map[str(row.conversation_id)] = row.cnt > 0
# Batch query 3: No-participant conversations (legacy notify flag)