forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat.py
More file actions
1475 lines (1255 loc) · 59 KB
/
Copy pathchat.py
File metadata and controls
1475 lines (1255 loc) · 59 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 copy
import hashlib
import json
import logging
import uuid
from datetime import datetime, timezone
from typing import Any, Dict, Iterator, List, Optional, cast
from google.api_core.exceptions import AlreadyExists, Conflict, FailedPrecondition, NotFound
from google.cloud import firestore, firestore_v1
from google.cloud.firestore_v1 import FieldFilter
from database.firestore_index_registry import (
CURRENT_CHAT_SESSION_ORDERED_QUERY,
CURRENT_CHAT_SESSION_QUERY,
)
# Sessions are per-user and per-app, so this is a ceiling on a small collection
# rather than a page size; it exists so a pathological account cannot turn one
# lookup into an unbounded read.
CURRENT_CHAT_SESSION_SCAN_LIMIT = 200
from models.chat import Message
from utils import encryption
from ._client import db
from .helpers import prepare_for_read, prepare_for_write, set_data_protection_level
from database.read_boundary import parse_snapshot_or_none
logger = logging.getLogger(__name__)
BATCH_LIMIT = 500 # Firestore hard limit
DELETE_MESSAGES_BATCH_LIMIT = 200 # Leaves room for one session-counter write per deleted message.
DELETE_MESSAGES_CONFLICT_RETRIES = 3
CHAT_HISTORY_BASE_VISIBLE_MESSAGES = 10
CHAT_HISTORY_APPEND_EPOCH_MESSAGES = 8
# Maximum number of reported (hidden) rows to over-fetch per raw Firestore
# query when reading cache-aligned history. Keeps the raw read bounded even
# when a user has thousands of lifetime reported messages; the newest page
# rarely contains more reported rows than this cap.
CHAT_HISTORY_REPORTED_RAW_SCAN_CAP = 50
# Extra documents a visible page may stream *beyond* the rows it would need if none
# were reported. The floor is the page itself, never this: the previous raw
# ``.offset(n).limit(m)`` query already streamed n + m documents, so budgeting
# ``needed + slack`` can only read more than before by the slack, and can never fail
# to service an offset the old query serviced. Capping the total instead made a deep
# offset return an empty page, which the router reads as end-of-results -- the same
# defect this scan exists to fix.
CHAT_MESSAGES_VISIBLE_PAGE_SCAN_SLACK = 1000
class ClientMessageIdPayloadConflict(ValueError):
"""The same client id was reused for a different immutable message."""
class MessageReconcileCursorError(ValueError):
"""A desktop journal cursor is absent or outside the authenticated scope."""
def _typed_doc(doc: Any) -> Dict[str, Any]:
"""Typed adapter for a Firestore DocumentSnapshot.to_dict() result.
Returns an empty dict when the document has no fields (None payload),
so callers can safely mutate and read keys without Optional checks.
"""
raw: object = doc.to_dict()
return cast(Dict[str, Any], raw) if isinstance(raw, dict) else {}
# *********************************
# ******* ENCRYPTION HELPERS ******
# *********************************
def _encrypt_chat_data(chat_data: Dict[str, Any], uid: str) -> Dict[str, Any]:
data = copy.deepcopy(chat_data)
if 'text' in data and isinstance(data['text'], str):
data['text'] = encryption.encrypt(data['text'], uid)
return data
def _decrypt_chat_data(chat_data: Dict[str, Any], uid: str) -> Dict[str, Any]:
data = copy.deepcopy(chat_data)
if 'text' in data and isinstance(data['text'], str):
try:
data['text'] = encryption.decrypt(data['text'], uid)
except Exception:
pass
return data
def _prepare_data_for_write(data: Dict[str, Any], uid: str, level: str) -> Dict[str, Any]:
if level == 'enhanced':
return _encrypt_chat_data(data, uid)
return data
def _prepare_message_for_read(message_data: Dict[str, Any], uid: str) -> Dict[str, Any]:
level = message_data.get('data_protection_level')
if level == 'enhanced':
return _decrypt_chat_data(message_data, uid)
return message_data
def decrypt_message_payload(message_data: Dict[str, Any], uid: str) -> Dict[str, Any]:
"""Public read-path decryption for one raw message document.
Callers outside this module (the feedback-report context hydrator) need the
same enhanced-protection handling `get_message` applies, but starting from a
raw snapshot dict they already hold. Exposed rather than reaching into the
private helper so the encryption contract has one owner.
"""
return _prepare_message_for_read(message_data, uid)
# *****************************
# ********** CRUD *************
# *****************************
@set_data_protection_level(data_arg_name='message_data')
@prepare_for_write(data_arg_name='message_data', prepare_func=_prepare_data_for_write)
def add_message(uid: str, message_data: Dict[str, Any]) -> Dict[str, Any]:
del message_data['memories']
user_ref = db.collection('users').document(uid)
user_ref.collection('messages').add(message_data)
return message_data
def add_app_message(text: str, app_id: str, uid: str, conversation_id: Optional[str] = None) -> Message:
"""Add a chat message an app posted for the user, linking it to that app's chat session so it
appears in the chat feed. get_messages filters by chat_session_id whenever a session exists, so
a message stored without one is never returned on that path."""
chat_session = get_chat_session(uid, app_id=app_id)
chat_session_id = chat_session['id'] if chat_session else None
ai_message = Message(
id=str(uuid.uuid4()),
text=text,
created_at=datetime.now(timezone.utc),
sender='ai', # type: ignore[reportArgumentType] # pydantic accepts str for MessageSender enum
app_id=app_id,
from_external_integration=False,
type='text', # type: ignore[reportArgumentType] # pydantic accepts str for MessageType enum
memories_id=[conversation_id] if conversation_id else [],
chat_session_id=chat_session_id,
)
add_message(uid, ai_message.model_dump())
if chat_session_id:
add_message_to_chat_session(uid, chat_session_id, ai_message.id)
return ai_message
def add_integration_chat_message(text: str, app_id: Optional[str], uid: str) -> Message:
"""Add a chat message from an external integration (e.g. notification API),
linking it to the user's existing chat session so it appears in the chat feed."""
chat_session = get_chat_session(uid, app_id=app_id)
chat_session_id = chat_session['id'] if chat_session else None
ai_message = Message(
id=str(uuid.uuid4()),
text=text,
created_at=datetime.now(timezone.utc),
sender='ai', # type: ignore[reportArgumentType] # pydantic accepts str for MessageSender enum
app_id=app_id,
from_external_integration=True,
type='text', # type: ignore[reportArgumentType] # pydantic accepts str for MessageType enum
chat_session_id=chat_session_id,
)
add_message(uid, ai_message.model_dump())
if chat_session_id:
add_message_to_chat_session(uid, chat_session_id, ai_message.id)
return ai_message
def add_summary_message(text: str, uid: str) -> Message:
ai_message = Message(
id=str(uuid.uuid4()),
text=text,
created_at=datetime.now(timezone.utc),
sender='ai', # type: ignore[reportArgumentType] # pydantic accepts str for MessageSender enum
app_id=None,
from_external_integration=False,
type='day_summary', # type: ignore[reportArgumentType] # pydantic accepts str for MessageType enum
memories_id=[],
)
add_message(uid, ai_message.model_dump())
return ai_message
@prepare_for_read(decrypt_func=_prepare_message_for_read)
def get_app_messages(
uid: str, app_id: str, limit: int = 20, include_conversations: bool = False
) -> List[Dict[str, Any]]:
"""Return an app's newest visible messages, up to ``limit``.
``reported`` is intentionally filtered in Python because the legacy data
model permits the field to be absent. The Firestore limit must therefore
not run before that visibility rule: a reported row inside the raw page
would otherwise consume a caller-visible slot and leave an older visible
message unfetched. This follows the same bounded visible-row scan as
``get_messages`` below.
"""
visible_limit = max(0, int(limit))
if visible_limit == 0:
return []
user_ref = db.collection('users').document(uid)
query: Any = (
user_ref.collection('messages')
.where(filter=FieldFilter('plugin_id', '==', app_id))
.order_by('created_at', direction=firestore.Query.DESCENDING)
)
# A clean page needs exactly ``visible_limit`` raw rows. Bound only the
# extra rows needed to cross reported records, so this cannot become an
# unbounded history read while a deep run of reported rows still has a
# flat allowance to cross.
scan_budget = visible_limit + CHAT_MESSAGES_VISIBLE_PAGE_SCAN_SLACK
scanned = 0
reported_row_seen = False
cursor_snapshot: Any = None
messages: List[Dict[str, Any]] = []
conversations_id: set[str] = set()
while scanned < scan_budget and len(messages) < visible_limit:
# A clean page reads exactly its requested visible rows, even when it
# needs more than one capped 100-row batch. Once a reported row has
# appeared, use capped batches to cross a dense hidden run without
# turning a missing visible row into one read per document.
batch_limit = min(100, scan_budget - scanned)
if not reported_row_seen:
batch_limit = min(batch_limit, max(1, visible_limit - len(messages)))
page_query = query.start_after(cursor_snapshot) if cursor_snapshot is not None else query
documents = list(page_query.limit(batch_limit).stream())
if not documents:
break
for document in documents:
scanned += 1
cursor_snapshot = document
message: Dict[str, Any] = _typed_doc(document)
if message.get('reported') is True:
reported_row_seen = True
continue
messages.append(message)
conversations_id.update(message.get('memories_id', []))
if len(messages) == visible_limit:
break
if len(documents) < batch_limit:
break
if not include_conversations:
return messages
# Fetch all conversations at once
conversations: Dict[str, Any] = {}
conversations_ref = user_ref.collection('conversations')
doc_refs = [conversations_ref.document(str(conversation_id)) for conversation_id in conversations_id]
docs = db.get_all(doc_refs)
for doc in docs:
if doc.exists:
conversation: Dict[str, Any] = _typed_doc(doc)
conversations[conversation['id']] = conversation
# Attach conversations to messages
for message in messages:
message['memories'] = [
conversations[conversation_id]
for conversation_id in message.get('memories_id', [])
if conversation_id in conversations
]
return messages
@prepare_for_read(decrypt_func=_prepare_message_for_read)
def get_messages(
uid: str,
limit: int = 20,
offset: int = 0,
include_conversations: bool = False,
app_id: Optional[str] = None,
chat_session_id: Optional[str] = None,
) -> List[Dict[str, Any]]:
"""Return a visible chat page with offset counted in non-reported rows.
Firestore cannot apply ``reported != True`` cheaply for legacy docs that omit
the field, so reported rows are filtered in Python. Applying ``limit`` /
``offset`` on the raw query first makes pages short and advances past
visible messages the client never saw. Scan with a bounded budget (same
spirit as ``get_messages_reconcile_page``) until ``offset`` visible rows are
skipped and ``limit`` visible rows are collected.
"""
logger.info(f'get_messages {uid} {limit} {offset} {app_id} {include_conversations}')
user_ref = db.collection('users').document(uid)
messages_ref = user_ref.collection('messages')
if chat_session_id:
# Session-scoped query: filter by session only, skip plugin_id filter
# because the session already determines which app the messages belong to.
messages_ref = messages_ref.where(filter=FieldFilter('chat_session_id', '==', chat_session_id))
else:
# App-scoped query: filter by plugin_id (None = main chat)
messages_ref = messages_ref.where(filter=FieldFilter('plugin_id', '==', app_id))
query: Any = messages_ref.order_by('created_at', direction=firestore.Query.DESCENDING)
# A page with no reported rows needs exactly this many documents, which is what the
# old raw query streamed. Bound the *slack* on top of it, not the page itself.
needed = max(offset, 0) + max(limit, 0)
# Flat slack, not proportional. Scaling it with the page size gave a small page a
# tiny allowance (limit=2 -> 6 documents), so a dense run of reported rows still
# returned an empty page the router reads as end-of-results. The read cost is set
# by the batch sizing below, not by this ceiling, so a flat allowance costs a clean
# page nothing and only bounds how far a page that meets reported rows may scan.
scan_budget = needed + CHAT_MESSAGES_VISIBLE_PAGE_SCAN_SLACK
scanned = 0
visible_skipped = 0
messages: List[Dict[str, Any]] = []
conversations_id: set[str] = set()
files_id: set[str] = set()
cursor_snapshot: Any = None
while scanned < scan_budget and len(messages) < limit:
# Read exactly what the page needs before reading any slack. Without this the
# first batch was a flat 100 documents, so the chat-send path's limit=5 and
# limit=15 reads streamed ~20x the documents they used to. Slack is only paid
# for by a page that actually met a reported row.
batch_limit = min(100, scan_budget - scanned)
if scanned == 0:
batch_limit = min(batch_limit, max(1, needed))
page_query = query.start_after(cursor_snapshot) if cursor_snapshot is not None else query
documents = list(page_query.limit(batch_limit).stream())
if not documents:
break
for document in documents:
scanned += 1
cursor_snapshot = document
message: Dict[str, Any] = _typed_doc(document)
if message.get('reported') is True:
continue
if visible_skipped < offset:
visible_skipped += 1
continue
messages.append(message)
conversations_id.update(message.get('memories_id', []))
files_id.update(message.get('files_id', []))
if len(messages) == limit:
break
if len(documents) < batch_limit:
break
if not include_conversations:
return messages
# Fetch all conversations at once
conversations: Dict[str, Any] = {}
conversations_ref = user_ref.collection('conversations')
doc_refs = [conversations_ref.document(str(conversation_id)) for conversation_id in conversations_id]
docs = db.get_all(doc_refs)
for doc in docs:
if doc.exists:
conversation: Dict[str, Any] = _typed_doc(doc)
conversations[conversation['id']] = conversation
# Attach conversations to messages
for message in messages:
message['memories'] = [
conversations[conversation_id]
for conversation_id in message.get('memories_id', [])
if conversation_id in conversations
]
# Fetch file chat
files: Dict[str, Any] = {}
files_ref = user_ref.collection('files')
files_ref = [files_ref.document(str(file_id)) for file_id in files_id]
doc_files = db.get_all(files_ref)
for doc in doc_files:
if doc.exists:
file: Dict[str, Any] = _typed_doc(doc)
files[file['id']] = file
# Attach files to messages
for message in messages:
message['files'] = [files[file_id] for file_id in message.get('files_id', []) if file_id in files]
return messages
def cache_aligned_history_limit(total_visible_messages: int) -> int:
"""Return a bounded history size whose start moves only at epoch boundaries.
A fixed newest-N window changes at the front on every chat turn, invalidating
Anthropic's cumulative message-prefix cache. This policy keeps at least the
existing ten-message continuity window and lets it grow append-only for eight
messages before resetting to ten. The request therefore carries 10..17
messages, never less history than before and never an unbounded transcript.
"""
if total_visible_messages < 0:
raise ValueError('total_visible_messages must be non-negative')
if total_visible_messages <= CHAT_HISTORY_BASE_VISIBLE_MESSAGES:
return total_visible_messages
return CHAT_HISTORY_BASE_VISIBLE_MESSAGES + (
(total_visible_messages - CHAT_HISTORY_BASE_VISIBLE_MESSAGES) % CHAT_HISTORY_APPEND_EPOCH_MESSAGES
)
def get_cache_aligned_messages(
uid: str,
*,
app_id: Optional[str] = None,
chat_session_id: Optional[str] = None,
) -> List[Dict[str, Any]]:
"""Read a cache-aligned, scope-safe chat history in newest-first order.
Reported messages are excluded from the visible count and read. Over-fetching
by the scoped reported count guarantees the target number of visible messages
even when hidden records fall inside the selected raw Firestore page.
"""
user_ref = db.collection('users').document(uid)
scoped_ref = user_ref.collection('messages')
if chat_session_id:
scoped_ref = scoped_ref.where(filter=FieldFilter('chat_session_id', '==', chat_session_id))
else:
scoped_ref = scoped_ref.where(filter=FieldFilter('plugin_id', '==', app_id))
total_result = scoped_ref.count().get()
total = int(total_result[0][0].value) if total_result and total_result[0] else 0
reported_result = scoped_ref.where(filter=FieldFilter('reported', '==', True)).count().get()
reported = int(reported_result[0][0].value) if reported_result and reported_result[0] else 0
visible_total = max(0, total - reported)
visible_limit = cache_aligned_history_limit(visible_total)
if visible_limit == 0:
return []
# Cap the raw Firestore read so a large lifetime reported count cannot
# cause unbounded document reads on every chat send. The over-fetch only
# needs to cover reported rows that fall inside the newest raw page, not
# the lifetime total.
reported_overfetch = min(reported, CHAT_HISTORY_REPORTED_RAW_SCAN_CAP)
raw_limit = min(total, visible_limit + reported_overfetch)
return get_messages(
uid,
limit=raw_limit,
app_id=app_id,
chat_session_id=chat_session_id,
)[:visible_limit]
@prepare_for_read(decrypt_func=_prepare_message_for_read)
def get_messages_reconcile_page(
uid: str,
*,
limit: int,
cursor_message_id: Optional[str] = None,
app_id: Optional[str] = None,
chat_session_id: Optional[str] = None,
) -> tuple[List[Dict[str, Any]], Optional[str], bool]:
"""Return a stable, owner-scoped keyset page for the desktop journal.
`get_messages` remains offset-compatible for existing clients. This path is
deliberately separate: a Firestore document snapshot cursor cannot skip or
duplicate rows when a newer message is inserted between page requests.
Reported rows are scanned but not returned, with a bounded scan budget and a
cursor over the last inspected document so filtering cannot stall progress.
"""
if limit < 1 or limit > 100:
raise ValueError('reconcile page limit must be between 1 and 100')
user_ref = db.collection('users').document(uid)
messages_collection = user_ref.collection('messages')
query: Any = messages_collection
if chat_session_id:
query = query.where(filter=FieldFilter('chat_session_id', '==', chat_session_id))
else:
query = query.where(filter=FieldFilter('plugin_id', '==', app_id))
query = query.order_by('created_at', direction=firestore.Query.DESCENDING)
cursor_snapshot: Any = None
if cursor_message_id:
cursor_snapshot = messages_collection.document(cursor_message_id).get()
if not cursor_snapshot.exists:
raise MessageReconcileCursorError('message cursor does not exist')
cursor_payload = _typed_doc(cursor_snapshot)
cursor_in_scope = (
cursor_payload.get('chat_session_id') == chat_session_id
if chat_session_id
else cursor_payload.get('plugin_id') == app_id
)
if not cursor_in_scope or cursor_payload.get('created_at') is None:
raise MessageReconcileCursorError('message cursor is outside the requested scope')
# Four pages of reported rows may be traversed per request. The returned
# cursor lets a caller resume if the bounded budget is exhausted.
scan_budget = min(1000, max(100, limit * 4))
scanned = 0
messages: List[Dict[str, Any]] = []
next_cursor = cursor_message_id
has_more = False
while scanned < scan_budget and len(messages) < limit:
batch_limit = min(100, scan_budget - scanned)
page_query = query.start_after(cursor_snapshot) if cursor_snapshot is not None else query
documents = list(page_query.limit(batch_limit).stream())
if not documents:
has_more = False
break
reached_return_limit = False
for document in documents:
scanned += 1
cursor_snapshot = document
next_cursor = str(document.id)
message = _typed_doc(document)
if message.get('reported') is not True:
messages.append(message)
if len(messages) == limit:
reached_return_limit = True
break
if reached_return_limit:
# An extra empty page is harmless when the last returned row was the
# collection tail; claiming continuation avoids a racey count query.
has_more = True
break
if len(documents) < batch_limit:
has_more = False
break
has_more = True
if scanned >= scan_budget and len(messages) < limit:
has_more = True
if next_cursor == cursor_message_id and not messages:
next_cursor = None
return messages, next_cursor, has_more
def get_message_count(uid: str) -> int:
"""Return the number of chat messages visible to the user.
Reported messages are hidden from every chat view (``get_messages`` and ``get_app_messages``
skip ``reported == True``), so this stat excludes them too; otherwise it would exceed the number
of messages the user can actually see anywhere. Uses count() aggregation (total minus the
reported subset) rather than streaming every message. A ``reported == False`` count would be
wrong because legacy messages may omit the field.
"""
messages_ref = db.collection('users').document(uid).collection('messages')
total_res = messages_ref.count().get()
total = int(total_res[0][0].value) if total_res and total_res[0] else 0
reported_res = messages_ref.where(filter=FieldFilter('reported', '==', True)).count().get()
reported = int(reported_res[0][0].value) if reported_res and reported_res[0] else 0
return max(0, total - reported)
def iter_all_messages(uid: str, batch_size: int = 1000) -> Iterator[Dict[str, Any]]:
"""Yield all chat messages for a user, decrypted, in batches. Used for streaming data export."""
user_ref = db.collection('users').document(uid)
msgs_ref = user_ref.collection('messages').order_by('created_at', direction=firestore.Query.DESCENDING)
cursor = None
while True:
batch_ref = msgs_ref.limit(batch_size)
if cursor is not None:
batch_ref = batch_ref.start_after(cursor)
batch: List[Dict[str, Any]] = []
snapshots = list(batch_ref.stream())
for doc in snapshots:
msg: Dict[str, Any] = _typed_doc(doc)
msg['id'] = doc.id
msg = _prepare_message_for_read(msg, uid) or msg
batch.append(msg)
yield from batch
if len(snapshots) < batch_size:
break
cursor = snapshots[-1]
def get_message(uid: str, message_id: str) -> tuple[Message, str] | None:
user_ref = db.collection('users').document(uid)
message_ref = user_ref.collection('messages').where('id', '==', message_id).limit(1).stream()
message_doc = next(message_ref, None)
if not message_doc:
return None
message = parse_snapshot_or_none(
Message,
message_doc,
payload_from_snapshot=lambda snapshot: _prepare_message_for_read(_typed_doc(snapshot), uid),
)
if message is None:
return None
return message, message_doc.id
def report_message(uid: str, msg_doc_id: str) -> Dict[str, str]:
user_ref = db.collection('users').document(uid)
message_ref = user_ref.collection('messages').document(msg_doc_id)
try:
message_ref.update({'reported': True})
return {"message": "Message reported"}
except Exception as e:
logger.error(f"Update failed: {e}")
return {"message": f"Update failed: {e}"}
def update_message_rating(uid: str, message_id: str, rating: Optional[int]) -> Optional[Dict[str, Any]]:
"""
Update the rating on a message document.
Returns the already-streamed message snapshot on success so analytics can
copy identifiers (notification kind, app_id) without a second Firestore read.
Returns None if the message does not exist.
"""
user_ref = db.collection('users').document(uid)
message_ref = user_ref.collection('messages').where('id', '==', message_id).limit(1).stream()
message_doc = next(message_ref, None)
if not message_doc:
logger.warning(f"⚠️ Message {message_id} not found for user {uid}")
return None
snapshot = _typed_doc(message_doc)
try:
user_ref.collection('messages').document(message_doc.id).update({'rating': rating})
logger.info(f"✅ Updated message {message_id} rating to {rating}")
snapshot['rating'] = rating
return snapshot
except Exception as e:
logger.error(f"❌ Failed to update message rating: {e}")
return None
def batch_delete_messages(
parent_doc_ref: Any, batch_size: int = 450, app_id: Optional[str] = None, chat_session_id: Optional[str] = None
) -> None:
messages_ref = parent_doc_ref.collection('messages')
messages_ref = messages_ref.where(filter=FieldFilter('plugin_id', '==', app_id))
if chat_session_id:
messages_ref = messages_ref.where(filter=FieldFilter('chat_session_id', '==', chat_session_id))
logger.info(f'batch_delete_messages {app_id}')
while True:
docs_stream = messages_ref.limit(batch_size).stream()
docs_list: List[Any] = list(docs_stream)
if not docs_list:
logger.info("No more messages to delete")
break
batch = db.batch()
for doc in docs_list:
batch.delete(doc.reference)
batch.commit()
logger.info(f'Deleted {len(docs_list)} messages')
if len(docs_list) < batch_size:
logger.info("Processed all messages")
break
def clear_chat(
uid: str, app_id: Optional[str] = None, chat_session_id: Optional[str] = None
) -> Optional[Dict[str, str]]:
try:
user_ref = db.collection('users').document(uid)
logger.info(f"Deleting messages for user: {uid}")
if not user_ref.get().exists:
return {"message": "User not found"}
batch_delete_messages(user_ref, app_id=app_id, chat_session_id=chat_session_id)
return None
except Exception as e:
return {"message": str(e)}
def add_multi_files(uid: str, files_data: List[Dict[str, Any]]) -> None:
batch = db.batch()
user_ref = db.collection('users').document(uid)
for file_data in files_data:
file_ref = user_ref.collection('files').document(file_data['id'])
batch.set(file_ref, file_data)
batch.commit()
def get_chat_files(uid: str, files_id: Optional[List[str]] = None) -> List[Dict[str, Any]]:
files_ref = db.collection('users').document(uid).collection('files')
if files_id is None:
files_id = []
# If no specific files requested, return all
if len(files_id) == 0:
return [_typed_doc(doc) for doc in files_ref.stream()]
# Firestore IN operator supports max 30 values, so chunk the queries
if len(files_id) <= 30:
files_ref = files_ref.where(filter=FieldFilter('id', 'in', files_id))
return [_typed_doc(doc) for doc in files_ref.stream()]
# Chunk into batches of 30
results: List[Dict[str, Any]] = []
for i in range(0, len(files_id), 30):
chunk = files_id[i : i + 30]
chunk_ref = db.collection('users').document(uid).collection('files')
chunk_ref = chunk_ref.where(filter=FieldFilter('id', 'in', chunk))
results.extend([_typed_doc(doc) for doc in chunk_ref.stream()])
return results
def get_chat_files_desc(uid: str, files_id: Optional[List[str]] = None, limit: int = 10) -> List[Dict[str, Any]]:
"""Get the most recent chat files ordered by created_at descending, optionally filtered by file IDs"""
files_ref = db.collection('users').document(uid).collection('files')
if files_id is None:
files_id = []
# If no specific files requested, return most recent files
if len(files_id) == 0:
files_ref = files_ref.order_by('created_at', direction=firestore.Query.DESCENDING).limit(limit)
return [_typed_doc(doc) for doc in files_ref.stream()]
# If specific files requested, filter by them first
# Firestore IN operator supports max 30 values
if len(files_id) <= 30:
files_ref = files_ref.where(filter=FieldFilter('id', 'in', files_id))
files_ref = files_ref.order_by('created_at', direction=firestore.Query.DESCENDING).limit(limit)
return [_typed_doc(doc) for doc in files_ref.stream()]
# Chunk into batches of 30 if more than 30 files
results: List[Dict[str, Any]] = []
for i in range(0, len(files_id), 30):
chunk = files_id[i : i + 30]
chunk_ref = db.collection('users').document(uid).collection('files')
chunk_ref = chunk_ref.where(filter=FieldFilter('id', 'in', chunk))
chunk_ref = chunk_ref.order_by('created_at', direction=firestore.Query.DESCENDING)
results.extend([_typed_doc(doc) for doc in chunk_ref.stream()])
# Sort all results by created_at and limit. Use a tz-aware sentinel for a missing created_at so it
# never TypeError-compares against the tz-aware Firestore datetimes and sinks to the bottom of the
# descending sort (same class as the review-queue tz sentinel in #9571).
results.sort(key=lambda x: x.get('created_at', datetime.min.replace(tzinfo=timezone.utc)), reverse=True)
return results[:limit]
def delete_multi_files(uid: str, files_data: List[Dict[str, Any]]) -> None:
batch = db.batch()
user_ref = db.collection('users').document(uid)
for file_data in files_data:
file_ref = user_ref.collection('files').document(file_data["id"])
batch.delete(file_ref)
batch.commit()
def add_chat_session(uid: str, chat_session_data: Dict[str, Any]) -> Dict[str, Any]:
user_ref = db.collection('users').document(uid)
user_ref.collection('chat_sessions').document(chat_session_data['id']).set(chat_session_data)
return chat_session_data
def get_chat_session(uid: str, app_id: Optional[str] = None) -> Optional[Dict[str, Any]]:
"""The user's current chat session for an app.
Newest-first: an unordered `.limit(1)` lets Firestore return any matching
document, so once a user has more than one session for an app the "current"
one is whichever the index happens to yield. Callers treat this as the
session to read and append to, so an arbitrary pick silently splits a
conversation across sessions.
The ordering is applied after the read, not by `order_by`, because Firestore
drops documents that lack the ordered field entirely. `add_chat_session`
writes whatever dict it is handed, so a session with no `created_at` is
representable — and ordering in the query would make those sessions
invisible here, stranding a user's existing history behind a brand new
session. A session with no timestamp sorts oldest, and its id breaks ties so
the answer is stable across calls.
"""
collection = db.collection('users').document(uid).collection('chat_sessions')
ordered_sessions = (
CURRENT_CHAT_SESSION_ORDERED_QUERY.build(
collection,
{'app_id': app_id},
field_filter_factory=FieldFilter,
)
.order_by('created_at', direction=firestore.Query.DESCENDING)
.order_by('__name__', direction=firestore.Query.DESCENDING)
.limit(1)
.stream()
)
ordered_docs = [_typed_doc(session) for session in ordered_sessions]
if ordered_docs:
return max(
ordered_docs,
key=lambda data: (
data.get('created_at') is not None,
data.get('created_at') or datetime.min.replace(tzinfo=timezone.utc),
str(data.get('id') or ''),
),
)
legacy_session = (
CURRENT_CHAT_SESSION_QUERY.build(
collection,
{'app_id': app_id},
field_filter_factory=FieldFilter,
)
.order_by('__name__', direction=firestore.Query.ASCENDING)
.limit(1)
.stream()
)
legacy_docs = [_typed_doc(session) for session in legacy_session]
if len(legacy_docs) > 1:
legacy_docs = legacy_docs[:1]
newest: Optional[Dict[str, Any]] = None
newest_key: Optional[tuple] = None
for data in legacy_docs:
# `_typed_doc` returns {} for a document with no fields, which sorts as
# untimestamped and loses to anything real rather than being skipped.
created = data.get('created_at')
key = (created is not None, created or datetime.min.replace(tzinfo=timezone.utc), str(data.get('id') or ''))
if newest_key is None or key > newest_key:
newest, newest_key = data, key
return newest
def get_chat_session_by_id(uid: str, chat_session_id: str) -> Optional[Dict[str, Any]]:
"""Get a specific chat session by its ID"""
user_ref = db.collection('users').document(uid)
session_ref = user_ref.collection('chat_sessions').document(chat_session_id)
session_doc = session_ref.get()
if session_doc.exists:
data = session_doc.to_dict()
data['id'] = chat_session_id
return _normalize_chat_session(data)
return None
def delete_chat_session(uid: str, chat_session_id: str, cascade_messages: bool = False) -> Optional[bool]:
user_ref = db.collection('users').document(uid)
session_ref = user_ref.collection('chat_sessions').document(chat_session_id)
if cascade_messages:
if not session_ref.get().exists:
return False
msg_col = user_ref.collection('messages')
query = msg_col.where(filter=FieldFilter('chat_session_id', '==', chat_session_id))
while True:
docs: List[Any] = list(query.limit(BATCH_LIMIT).stream())
if not docs:
break
batch = db.batch()
for doc in docs:
batch.delete(msg_col.document(doc.id))
batch.commit()
session_ref.delete()
return None
def _update_chat_session_if_exists(uid: str, chat_session_id: str, values: Dict[str, Any], what: str) -> bool:
"""Apply a derived-state update to a chat session, tolerating a deleted session.
The message/file id lists and the OpenAI ids are derived state the session
document owns. Every writer below runs after a multi-second LLM call, and
DELETE /v2/messages (clear chat) deletes the session it read at the start of
that same window — so a concurrent clear, or a client retrying the slow
request, leaves these writes pointing at a tombstone. Firestore's update()
then raises NotFound and the user's chat call 500s even though the work it
was reporting already succeeded. A session that no longer exists has nothing
to record.
Returns True when the update was applied.
"""
session_ref = db.collection('users').document(uid).collection('chat_sessions').document(chat_session_id)
try:
session_ref.update(values)
return True
except NotFound:
logger.warning(f"chat session {chat_session_id} no longer exists; skipping {what}")
return False
def add_message_to_chat_session(uid: str, chat_session_id: str, message_id: str) -> None:
_update_chat_session_if_exists(
uid, chat_session_id, {"message_ids": firestore.ArrayUnion([message_id])}, "message link"
)
def add_files_to_chat_session(uid: str, chat_session_id: str, file_ids: List[str]) -> None:
if not file_ids:
return
_update_chat_session_if_exists(uid, chat_session_id, {"file_ids": firestore.ArrayUnion(file_ids)}, "file link")
# **************************************
# ********* MIGRATION HELPERS **********
# **************************************
def get_chats_to_migrate(uid: str, target_level: str) -> List[Dict[str, Any]]:
"""
Finds all chat messages that are not at the target protection level by fetching all documents
and filtering them in memory. This simplifies the code but may be less performant for
users with a very large number of documents.
"""
messages_ref = db.collection('users').document(uid).collection('messages')
all_messages = messages_ref.select(['data_protection_level']).stream()
to_migrate: List[Dict[str, Any]] = []
for doc in all_messages:
doc_data: Dict[str, Any] = _typed_doc(doc)
current_level = doc_data.get('data_protection_level', 'standard')
if target_level != current_level:
to_migrate.append({'id': doc.id, 'type': 'chat'})
return to_migrate
def migrate_chats_level_batch(uid: str, message_doc_ids: List[str], target_level: str) -> None:
"""
Migrates a batch of chat messages to the target protection level.
"""
batch = db.batch()
messages_ref = db.collection('users').document(uid).collection('messages')
doc_refs = [messages_ref.document(msg_id) for msg_id in message_doc_ids]
doc_snapshots = db.get_all(doc_refs)
for doc_snapshot in doc_snapshots:
if not doc_snapshot.exists:
logger.warning(f"Message {doc_snapshot.id} not found, skipping.")
continue
message_data: Dict[str, Any] = _typed_doc(doc_snapshot)
current_level = message_data.get('data_protection_level', 'standard')
if current_level == target_level:
continue
plain_data: Dict[str, Any] = _prepare_message_for_read(message_data, uid)
plain_text = plain_data.get('text')
migrated_text = plain_text
if target_level == 'enhanced':
if isinstance(plain_text, str):
migrated_text = encryption.encrypt(plain_text, uid)
update_data: Dict[str, Any] = {'data_protection_level': target_level, 'text': migrated_text}
batch.update(doc_snapshot.reference, update_data)
batch.commit()
# ============================================================================
# CHAT SESSIONS (v2)
#
# v2 sessions support: title, preview, message_count, starred, updated_at.
# v1 sessions store: message_ids, file_ids (legacy docs may still carry openai_thread_id).
# Both schemas coexist in the same Firestore collection.
# Both MUST write plugin_id alongside app_id for cross-platform query compat.
# ============================================================================
def _normalize_chat_session(data: Optional[dict]) -> Optional[dict]:
"""Guarantee a v2 chat-session dict satisfies ``ChatSessionResponse``.
Firestore holds sessions written by several code paths (Python v2, the Rust
desktop backend, legacy docs). Some rows are missing fields the response
model requires (``title``, ``created_at``, ``message_count``, ``starred``),
which makes FastAPI raise ``ResponseValidationError`` (HTTP 500). Fill safe
defaults so listing/reading sessions never 500 on an incomplete doc.
"""
if data is None:
return None
data.setdefault('title', 'New Chat')
data.setdefault('preview', None)
data.setdefault('message_count', 0)
data.setdefault('starred', False)
# created_at/updated_at are required datetimes; fall back to each other when
# one is missing (the list query orders by updated_at, so it is present there).
if data.get('created_at') is None:
data['created_at'] = data.get('updated_at') or datetime.now(timezone.utc)
if data.get('updated_at') is None:
data['updated_at'] = data.get('created_at') or datetime.now(timezone.utc)
return data