forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconversations.py
More file actions
2210 lines (1898 loc) · 96.5 KB
/
Copy pathconversations.py
File metadata and controls
2210 lines (1898 loc) · 96.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 asyncio
import hashlib
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response, BackgroundTasks
from typing import Any, Dict, List, Optional
from datetime import datetime, timezone
import database.conversations as conversations_db
import database._client as db_client_module
import database.action_items as action_items_db
import database.redis_db as redis_db
import database.users as users_db
from database.firestore_read_metrics import FirestoreReadSite
from database.vector_db import delete_vector, delete_transcript_chunk_vectors
import database.vector_db as vector_db
from utils.other.storage import delete_conversation_audio_files
from utils.screen_frames.store import delete_conversation_screen_frames
from models.calendar_context import CalendarMeetingContext
from models.client_processing import PROJECTION_FAMILY_FIELDS, ClientProcessing
from models.conversation import (
BulkAssignSegmentsRequest,
CalendarEventLink,
Conversation,
ConversationAnalytics,
ConversationFinalizationStatusResponse,
ConversationMutationResponse,
CreateConversationResponse,
DeleteActionItemRequest,
MergeConversationsRequest,
MergeConversationsResponse,
SearchRequest,
SetConversationActionItemsStateRequest,
SetConversationEventsStateRequest,
SharedConversationResponse,
TestPromptRequest,
TranscriptMatchSnippet,
UpdateActionItemDescriptionRequest,
UpdateSegmentTextRequest,
UpdateSummaryRequest,
project_shared_conversation,
)
from utils.conversations.factory import deserialize_conversation
from utils.conversations.analytics import build_conversation_analytics
from utils.conversations.render import redact_conversations_for_list
from utils.conversations.mcp_transcript_search import (
attach_match_snippets_to_conversations,
merge_typesense_page_with_transcript_hits,
search_transcript_conversation_ids,
)
from models.conversation_enums import ConversationStatus, ConversationVisibility
from models.conversation_photo import ConversationPhoto
from models.geolocation import Geolocation
from models.app import App
from pydantic import BaseModel, Field, ValidationError
from models.transcript_segment import TranscriptSegment
from models.other import Person
from models.shared import StatusResponse
from utils.conversations.projection_payload import (
client_processing_mutation,
sanitize_untrusted_provenance_field,
)
from utils.conversations.process_conversation import (
AppUsageAttribution,
DerivedEffectsDisposition,
process_conversation,
run_first_open_derived_work,
retrieve_in_progress_conversation,
)
from utils.conversations import lifecycle as lifecycle_service
from utils.conversations import share_email
from utils.conversations.meeting_receipt import record_and_persist_finalized_meeting_receipt
from utils.integration_telemetry import emit_posthog_event
from utils.executors import db_executor, llm_executor, postprocess_executor, run_blocking, submit_with_context
from utils.memory.memory_service import MemoryService
from utils.memory.retraction_scope import retraction_can_be_skipped
from utils.memory.canonical_memory_adapter import ConversationReplacementConflictError
from utils import byok
from utils.conversations.search import (
ConversationSearchUnavailableError,
clamp_conversation_search_pagination,
conversation_matches_date_range,
conversation_matches_speaker,
parse_exact_conversation_reference,
search_conversations,
)
from utils.llm.conversation_processing import SummaryProviderError, generate_summary_with_prompt
from utils.speaker_identification import extract_speaker_samples
from utils.other import endpoints as auth
from utils.other.storage import get_conversation_recording_if_exists
from utils.app_integrations import trigger_external_integrations
from utils.request_validation import NonNegativeOffset, PositiveLimit
from utils.journey_metrics_contract import resolve_client_kind
from utils.product_telemetry import emit_product_event
from services.conversation_frame_evidence import delete_conversation_and_frame_evidence
from utils.other.list_budget import (
OMI_LIST_TRUNCATED_HEADER,
OMI_LIST_TRUNCATED_VALUE,
list_read_budget_for_request,
)
from utils.conversations.calendar_linking import (
get_overlapping_calendar_event,
write_conversation_link_to_calendar_event,
)
from utils.conversations.calendar_utils import extract_attendees, parse_event_times
from utils.retrieval.tools.calendar_tools import get_google_calendar_event
from utils.retrieval.tools.google_utils import refresh_google_token
from utils.conversations.location import resolve_geolocation
from utils.conversations.transcript_hash import transcript_sha256_for_binding
from utils.observability.fallback import record_fallback
import logging
logger = logging.getLogger(__name__)
router = APIRouter()
def _get_valid_conversation_by_id(uid: str, conversation_id: str) -> dict:
conversation = conversations_db.get_conversation(
uid, conversation_id, read_site=FirestoreReadSite.CONVERSATIONS_VALID_BY_ID
)
if conversation is None:
raise HTTPException(status_code=404, detail="Conversation not found")
if conversation.get('is_locked', False):
raise HTTPException(status_code=402, detail="A paid plan is required to access this conversation.")
return conversation
def _speaker_assignment(segment: TranscriptSegment) -> str:
if segment.is_user:
return 'self'
if segment.person_id:
return f"person:{hashlib.sha256(str(segment.person_id).encode('utf-8')).hexdigest()[:16]}"
return 'unassigned'
def _speaker_assignment_kind(assignment: str) -> str:
return 'person' if assignment.startswith('person:') else assignment
def _emit_speaker_identity_confirmed(
*,
uid: str,
conversation_id: str,
scope: str,
before: List[str],
after: List[str],
) -> None:
if not after:
return
assignment_kinds = [_speaker_assignment_kind(value) for value in after]
properties = {
'conversation_id': conversation_id,
'confirmation': 'accepted' if before == after else 'corrected',
'assignment': assignment_kinds[0] if len(set(assignment_kinds)) == 1 else 'mixed',
'scope': scope,
'affected_segment_count': len(after),
}
if len(set(after)) == 1 and assignment_kinds[0] == 'person':
properties['assignment_id'] = after[0]
emit_product_event(
uid=uid,
event='Speaker Identity Confirmed',
properties=properties,
)
def _enrich_deferred_conversation(uid: str, conversation: dict) -> dict:
"""First open of a lazily-deferred desktop conversation. The LLM enrichment (summary, action
items, memories, embeddings, app results) takes ~10s, so we run it in the BACKGROUND and return
the conversation immediately: the client gets an instant open (transcript already present) and
polls until `status` flips to `completed`. The `deferred` flag is cleared atomically with the
admission-lease renewal so the stale-processing sweep cannot terminalize the row between clear
and first heartbeat. On enrichment failure the flag is re-armed and status reset to completed
so the next open retries cleanly instead of spinning."""
conversation_id = conversation.get('id')
try:
reacquired = lifecycle_service.reacquire_deferred_processing(uid, conversation_id)
except Exception as e:
logger.error(f"lazy enrich reacquire failed uid={uid} conv={conversation_id}: {e}")
return conversation
if not reacquired:
# The row was terminalized or discarded before reacquisition. A stale
# processor must not persist derived side effects after ownership loss.
return conversation
def _run_enrichment():
try:
conv_obj = deserialize_conversation(conversation)
conv_obj.deferred = False
with lifecycle_service.processing_admission_guard(uid, conversation_id, rollback_on_failure=False):
enriched = process_conversation(
uid,
conv_obj.language or 'en',
conv_obj,
force_process=True,
is_reprocess=False,
app_usage_attribution=AppUsageAttribution.NON_USER_REPROCESS,
)
# Deferred desktop meetings must publish their exact Chat receipt
# at the same terminal transition as ordinary finalization. The
# initial lazy row deliberately skipped this adapter, so doing it
# here closes the gap without waking Chat for processing rows.
if enriched is not None:
record_and_persist_finalized_meeting_receipt(uid, enriched)
logger.info(f"lazy enrich complete uid={uid} conv={conversation_id}")
except Exception as e:
logger.error(f"lazy enrich failed uid={uid} conv={conversation_id}: {e}")
try:
recovered = lifecycle_service.recover_deferred_processing_failure(uid, conversation_id)
if not recovered:
logger.warning(
'lazy enrich recovery lost ownership uid=%s conv=%s',
uid,
conversation_id,
)
except Exception:
logger.exception(
'lazy enrich recovery failed uid=%s conv=%s',
uid,
conversation_id,
)
submit_with_context(postprocess_executor, _run_enrichment)
# Return immediately — still status=processing, no summary yet; the client polls for completion.
conversation['deferred'] = False
return conversation
def _dispatch_first_open_work(uid: str, conversation: dict) -> None:
"""Claim once and run in the background; failure remains retryable."""
conversation_id = conversation.get('id')
if not conversation_id or not conversation.get('jit_first_open'):
return
try:
token = conversations_db.claim_authorized_first_open_work(uid, conversation_id, conversation.get('source'))
except Exception as error:
logger.warning('JIT first-open claim failed uid=%s conv=%s: %s', uid, conversation_id, error)
return
if token is None:
return
def _run() -> None:
succeeded = False
try:
latest = conversations_db.get_conversation(uid, conversation_id)
if latest is None:
raise RuntimeError('conversation disappeared before first-open work')
run_first_open_derived_work(uid, latest, token)
succeeded = True
except Exception as error:
logger.exception('JIT first-open worker failed uid=%s conv=%s: %s', uid, conversation_id, error)
finally:
try:
conversations_db.finish_first_open_work(uid, conversation_id, token, succeeded=succeeded)
except Exception as error:
logger.exception(
'JIT first-open lease finalization failed uid=%s conv=%s: %s', uid, conversation_id, error
)
submit_with_context(postprocess_executor, _run)
class ProcessConversationRequest(BaseModel):
calendar_meeting_context: Optional[CalendarMeetingContext] = None
# Unvalidated on purpose: a malformed projection must not 422 a finished recording.
# Schema, size caps, and transcript-hash binding run in the handler.
client_processing: Optional[Any] = Field(
default=None,
description=(
"Untrusted client-authored display projection. Accepted as a raw payload "
"and validated in the handler so a malformed projection cannot 422 a "
"finished recording. Hash-bound to the persisted transcript. Display only "
"— never an input to intelligence."
),
)
# Provenance is untrusted client input. Bound it before it reaches a log
# record so a newline / C0 control / oversized token cannot forge a second line.
def _projection_provenance_for_log(raw: Any) -> tuple[Any, Any, Any]:
"""Pull provenance for logs. Never raises; never returns body text."""
try:
if raw is None or isinstance(raw, (str, bytes, list, tuple, int, float, bool)):
return None, None, None
if isinstance(raw, dict):
provenance = raw.get('provenance')
else:
provenance = getattr(raw, 'provenance', None)
if provenance is None or isinstance(provenance, (str, bytes, list, tuple, int, float, bool)):
return None, None, None
if isinstance(provenance, dict):
return (
sanitize_untrusted_provenance_field(provenance.get('model_id')),
sanitize_untrusted_provenance_field(provenance.get('runtime')),
sanitize_untrusted_provenance_field(provenance.get('device_class')),
)
return (
sanitize_untrusted_provenance_field(getattr(provenance, 'model_id', None)),
sanitize_untrusted_provenance_field(getattr(provenance, 'runtime', None)),
sanitize_untrusted_provenance_field(getattr(provenance, 'device_class', None)),
)
except Exception:
return None, None, None
def _log_client_projection_rejected(reason: str, raw: Any) -> None:
"""Content-free reject log. Provenance may be missing or malformed."""
try:
model_id, runtime, device_class = _projection_provenance_for_log(raw)
logger.warning(
'client_processing rejected reason=%s model_id=%s runtime=%s device_class=%s',
reason,
model_id,
runtime,
device_class,
)
except Exception:
logger.warning('client_processing rejected reason=%s', reason)
def _accepted_client_projection(raw: Any, segments: Any) -> Optional[ClientProcessing]:
"""Bind a client projection to the persisted transcript, or drop it.
Schema failures and hash mismatch are not request errors: the conversation
still finalizes on the deterministic minimum. Warnings are content-free
(reason plus provenance only — never transcript or body).
"""
if raw is None:
return None
try:
projection = ClientProcessing.model_validate(raw)
except (TypeError, ValidationError, ValueError):
_log_client_projection_rejected('schema_invalid', raw)
return None
# Stored rows only: every caller here binds against a persisted transcript.
# `transcript_sha256_for_binding` returns None for a legacy row whose stored
# identity is not canonical -- for those, a matching digest would not imply
# matching rendered attribution, so the projection is dropped, not trusted.
expected = transcript_sha256_for_binding(segments or [])
if expected is None:
_log_client_projection_rejected('stored_transcript_not_canonical', raw)
return None
if expected != projection.transcript_sha256:
_log_client_projection_rejected('hash_mismatch', raw)
return None
return projection
def _drop_display_projection(conversation: Conversation) -> None:
"""Clear the in-memory projection after a transcript mutation invalidated storage.
Consults ``PROJECTION_FAMILY_FIELDS`` rather than naming the field, so a
sibling projection classified there is dropped here too without a code change.
"""
for field in PROJECTION_FAMILY_FIELDS:
setattr(conversation, field, None)
# Must match database.conversations.CLIENT_PROCESSING_BIND_REPORT_KEY.
# Local copy: this router is loaded under a stubbed database.conversations.
_CLIENT_PROCESSING_BIND_REPORT_KEY = '_client_processing_bind_report'
def _projection_bind_report() -> dict[str, bool]:
return {'submitted_projection_bound': False}
def _carry_projection_bind_report(extra_updates: dict[str, Any]) -> dict[str, bool]:
"""Attach an out-parameter the transactional bind fills. Never persisted."""
report = _projection_bind_report()
extra_updates[_CLIENT_PROCESSING_BIND_REPORT_KEY] = report
return report
def _echo_submitted_projection_if_bound(
conversation: Conversation,
client_projection: Optional[ClientProcessing],
bind_report: dict[str, bool],
) -> Optional[ClientProcessing]:
"""Attach the submitted projection only when THIS transaction stored it.
The bind report is the transaction's answer. A later request's projection
on the document is not this request's, and a rejected candidate must not
appear in the response.
"""
if client_projection is not None and bind_report.get('submitted_projection_bound') is True:
conversation.client_processing = client_projection
return client_projection
return None
def _bind_late_client_projection(uid: str, conversation: Conversation, raw: Any) -> Conversation:
"""Idempotency hit: bind a late projection to the stored transcript.
Updates only ``client_processing``. Never touches ``structured``, never
re-enters processing, never reprocesses. Invalid, mismatched, or missing
projection: return the existing conversation unchanged (still not a 422).
The write re-checks the digest against the transactional snapshot so a
T2 segment update cannot resurrect a T1 projection.
"""
if raw is None:
return conversation
bound = _accepted_client_projection(raw, getattr(conversation, 'transcript_segments', None))
if bound is None:
return conversation
# Route-level hash is a fast drop. The write re-checks the stored
# transcript inside the same transaction so a T2 segment update that
# landed after this snapshot cannot resurrect a T1 projection.
payload = client_processing_mutation(bound)
if conversations_db.bind_client_processing(uid, conversation.id, payload):
conversation.client_processing = bound
return conversation
class ConversationSearchItem(Conversation):
"""Search hit: base conversation fields plus optional transcript match evidence."""
match_snippets: List[TranscriptMatchSnippet] = []
class SearchConversationsResponse(BaseModel):
items: List[ConversationSearchItem]
total_pages: int
current_page: int
per_page: int
class ConversationStatusResponse(BaseModel):
status: str
class ConversationsCountResponse(BaseModel):
count: int
sources: List[str] | None = None
class ConversationRecordingResponse(BaseModel):
has_recording: bool
class ConversationSuggestedAppsResponse(BaseModel):
suggested_apps: List[App]
conversation_id: str
class ConversationTestPromptResponse(BaseModel):
summary: str
@router.post("/v1/conversations", response_model=CreateConversationResponse, tags=['conversations'])
def process_in_progress_conversation(
request: ProcessConversationRequest = None,
uid: str = Depends(auth.with_rate_limit(auth.get_current_user_uid, "conversations:create")),
):
conversation = retrieve_in_progress_conversation(uid)
if not conversation:
raise HTTPException(status_code=404, detail="Conversation in progress not found")
conversation = deserialize_conversation(conversation)
# Inject calendar context if provided
if request and request.calendar_meeting_context:
if not conversation.external_data:
conversation.external_data = {}
conversation.external_data['calendar_meeting_context'] = request.calendar_meeting_context.model_dump()
client_projection = _accepted_client_projection(
request.client_processing if request is not None else None,
getattr(conversation, 'transcript_segments', None),
)
# Geolocation
if conversation.geolocation:
conversation.geolocation = resolve_geolocation(conversation.geolocation)
else:
geolocation = redis_db.get_cached_user_geolocation(uid)
if geolocation:
record_fallback(
component='conversation_finalization',
from_mode='conversation_snapshot',
to_mode='redis_user_cache',
reason='other',
outcome='degraded',
log=logger,
)
conversation.geolocation = resolve_geolocation(Geolocation(**geolocation))
# Winner owns ingress. The accepted projection rides the admission CAS:
# status→processing and client_processing are one write. A later request
# (including a loser that late-binds) can only land after this commit, so
# a stalled second write cannot last-writer-wins an older projection over
# a newer one (section 1.7 (c)). A mutation failure is an admission
# failure — the row stays in_progress instead of stranding on processing
# with no durable job. Ingress-owned mutation only; the coordinator's
# existing-row persist still strips the field. Omit extra_updates when
# there is no projection so positional admit stubs keep working.
extra_updates = client_processing_mutation(client_projection) if client_projection is not None else None
bind_report = _projection_bind_report()
if extra_updates is None:
admitted = lifecycle_service.admit_processing(uid, conversation.id)
else:
bind_report = _carry_projection_bind_report(extra_updates)
admitted = lifecycle_service.admit_processing(uid, conversation.id, extra_updates=extra_updates)
if not admitted:
latest = _get_valid_conversation_by_id(uid, conversation.id)
latest_conversation = deserialize_conversation(latest)
# Losing the compare-and-swap still 200s, but must not silently drop a
# valid projection. Hash-bind against the conversation actually stored
# and write client_processing alone — never structured, never reprocess.
latest_conversation = _bind_late_client_projection(
uid,
latest_conversation,
request.client_processing if request is not None else None,
)
return CreateConversationResponse(conversation=latest_conversation, messages=[])
# The admission CAS reports whether the submitted projection bound.
# A follow-up read would race a later request's write and could strand
# this row on processing if it raised before the guard.
client_projection = _echo_submitted_projection_if_bound(conversation, client_projection, bind_report)
current_in_progress_id = redis_db.get_in_progress_conversation_id(uid)
if current_in_progress_id == conversation.id:
redis_db.remove_in_progress_conversation_id(uid)
conversation.status = ConversationStatus.processing
persisted = False
derived_effects_disposition = DerivedEffectsDisposition.RUN
def record_persistence(current: bool) -> None:
nonlocal persisted
persisted = current
def record_derived_effects_disposition(current: DerivedEffectsDisposition) -> None:
nonlocal derived_effects_disposition
derived_effects_disposition = current
# This synchronous path has no durable job for the reconciler to replay, so
# a processing failure must return the admission to in_progress — otherwise
# the conversation is stranded on "processing" forever and the client shows
# a stuck Processing card it can never resolve.
with lifecycle_service.processing_admission_guard(uid, conversation.id):
conversation = process_conversation(
uid,
conversation.language,
conversation,
force_process=True,
persistence_observer=record_persistence,
derived_effects_disposition_observer=record_derived_effects_disposition,
client_projection=client_projection,
)
if not persisted:
latest = _get_valid_conversation_by_id(uid, conversation.id)
return CreateConversationResponse(conversation=deserialize_conversation(latest), messages=[])
# A terminal free-tier minimum persists successfully but must not fan out
# apps/webhooks — the same decision the durable finalizer already honours
# via derived_effects_disposition_observer (section 1.7). The conversation
# itself still returns to the client; this suppresses derived effects only.
if derived_effects_disposition == DerivedEffectsDisposition.TERMINAL_NO_DERIVED_EFFECTS:
return CreateConversationResponse(conversation=conversation, messages=[])
messages = asyncio.run(trigger_external_integrations(uid, conversation))
return CreateConversationResponse(conversation=conversation, messages=messages)
@router.post(
'/v1/conversations/{conversation_id}/finalize', response_model=CreateConversationResponse, tags=['conversations']
)
def finalize_conversation(
conversation_id: str,
request: ProcessConversationRequest = None,
uid: str = Depends(auth.with_rate_limit(auth.get_current_user_uid, "conversations:create")),
):
"""Finalize exactly one backend conversation.
Unlike POST /v1/conversations, this does not operate on the user's Redis
"current in-progress" pointer, so desktop retry/rotation cannot accidentally
finalize a newer recording.
"""
conversation = _get_valid_conversation_by_id(uid, conversation_id)
conversation = deserialize_conversation(conversation)
if conversation.status != ConversationStatus.in_progress:
# Section 1.7 (c): a later projection overwrites projection fields only.
# A slow device finishing local inference after the first finalize is
# the normal case — hash-bind against the stored transcript and persist
# client_processing alone. Never rewrite structured, never re-enter
# processing, never reprocess. Mismatch / invalid: drop, still 200.
conversation = _bind_late_client_projection(
uid,
conversation,
request.client_processing if request is not None else None,
)
return CreateConversationResponse(conversation=conversation, messages=[])
extra_updates = {}
if request and request.calendar_meeting_context:
if not conversation.external_data:
conversation.external_data = {}
conversation.external_data['calendar_meeting_context'] = request.calendar_meeting_context.model_dump()
extra_updates['external_data'] = conversation.external_data
# Persist an accepted projection on the conversation document so the
# Cloud Tasks worker's stored-projection has_projection path can see it.
# Drop-never-422: a bad payload must not reject the finished recording.
# Do not attach yet: the outbox transaction re-checks the digest and may
# drop a T1-validated candidate after a T2 race.
client_projection = _accepted_client_projection(
request.client_processing if request is not None else None,
getattr(conversation, 'transcript_segments', None),
)
bind_report = _projection_bind_report()
if client_projection is not None:
extra_updates.update(client_processing_mutation(client_projection))
bind_report = _carry_projection_bind_report(extra_updates)
# The durable Cloud Tasks worker cannot inherit this request's BYOK
# context: the task payload is the opaque {job_id, dispatch_generation}
# schema, so the worker runs without the X-BYOK-* keys the middleware
# validated for this request. Admitting a BYOK request here would silently
# process the conversation with platform credentials. Reject before any
# mutation so BYOK clients fail fast instead of being processed as Omi keys.
if byok.has_byok_keys():
raise HTTPException(
status_code=409,
detail='BYOK finalization is not supported on this route; use the live listen session',
)
try:
finalization = lifecycle_service.request_finalization(
uid,
conversation.id,
has_byok_keys=False,
force_process=True,
extra_updates=extra_updates or None,
require_cloud_tasks=True,
client_kind=resolve_client_kind(x_app_platform=conversation.client_platform, user_agent=None),
)
except lifecycle_service.FinalizationDispatchUnavailable as error:
raise HTTPException(status_code=503, detail='Conversation finalization is temporarily unavailable') from error
if finalization['route'] == 'noop':
latest = _get_valid_conversation_by_id(uid, conversation_id)
return CreateConversationResponse(conversation=deserialize_conversation(latest), messages=[])
# Requiring Cloud Tasks keeps REST finalization off the pusher-only route.
# The only accepted outcomes are an enqueued task or an outbox row retained
# for reconciler retry after an uncertain task-create acknowledgement.
if finalization['route'] not in {'cloud_tasks', 'queued'}:
raise HTTPException(status_code=503, detail='Conversation finalization is temporarily unavailable')
conversation.status = ConversationStatus.processing
current_in_progress_id = redis_db.get_in_progress_conversation_id(uid)
if current_in_progress_id == conversation_id:
redis_db.remove_in_progress_conversation_id(uid)
# The outbox transaction reports whether the submitted projection bound.
# A follow-up read would attribute a later request's projection to this one.
_echo_submitted_projection_if_bound(conversation, client_projection, bind_report)
# The Cloud Tasks worker owns expensive processing, memory extraction, and
# integration fanout under the persisted job lease. Returning this snapshot
# is intentionally prompt; clients may poll the status projection below.
return CreateConversationResponse(conversation=conversation, messages=[])
@router.get(
'/v1/conversations/{conversation_id}/finalization',
response_model=ConversationFinalizationStatusResponse,
tags=['conversations'],
)
def get_conversation_finalization_status(
conversation_id: str,
uid: str = Depends(auth.get_current_user_uid),
):
_get_valid_conversation_by_id(uid, conversation_id)
status = lifecycle_service.get_finalization_status(uid, conversation_id)
if status is None:
raise HTTPException(status_code=404, detail='Conversation finalization job not found')
return status
@router.post(
'/v1/conversations/{conversation_id}/reprocess',
response_model=Conversation,
responses={
400: {'description': 'The selected app cannot summarize conversations'},
403: {'description': 'The selected app is not available to this user'},
404: {'description': 'The conversation or selected app does not exist'},
409: {'description': 'The selected app is disabled or not enabled by this user'},
},
tags=['conversations'],
)
def reprocess_conversation(
conversation_id: str,
language_code: Optional[str] = None,
app_id: Optional[str] = None,
uid: str = Depends(auth.with_rate_limit(auth.get_current_user_uid, "conversations:reprocess")),
):
"""
Whenever a user wants to reprocess a conversation, or wants to force process a discarded one
:param conversation_id: The ID of the conversation to reprocess
:param language_code: Optional language code to use for processing
:param app_id: Optional app ID to use for processing (if provided, only this app will be triggered)
:return: The updated conversation after reprocessing.
"""
conversation = _get_valid_conversation_by_id(uid, conversation_id)
# Reprocess force-processes a *discarded* conversation to revive it, but a
# soft-deleted tombstone is invisible to the user and must not be reprocessed:
# process_conversation would regenerate structured data, action items, memories
# and embeddings from content the user deleted, resurrecting it. Same
# tombstone-eligibility contract as sync (#10119) and merge (#10262). Checked
# on the raw doc because the Conversation model does not carry `deleted`.
if conversations_db.is_soft_deleted(conversation):
raise HTTPException(status_code=404, detail="Conversation not found")
conversation = deserialize_conversation(conversation)
if not language_code:
language_code = conversation.language or 'en'
explicit_app = _validate_reprocess_app_selection(uid, app_id) if app_id else None
processed_conversation = process_conversation(
uid,
language_code,
conversation,
force_process=True,
is_reprocess=True,
bypass_jit_first_open=True,
app_id=app_id,
explicit_app=explicit_app,
app_usage_attribution=(
AppUsageAttribution.EXPLICIT_SELECTION if explicit_app else AppUsageAttribution.NON_USER_REPROCESS
),
)
return processed_conversation
def _validate_reprocess_app_selection(uid: str, app_id: str) -> App:
"""Resolve one explicit selection before reprocessing mutates the conversation."""
# Imported here, not at module scope, for the same reason line ~1510 already does: the
# apps chain pulls the memory/social graph at import time, and the sanctioned isolation
# seam (backend/docs/test_isolation.md) loads this router bare to test pure request
# validation. A module-level import would make those suites stub a graph they never call.
from database.apps import get_app_by_id_db
from utils.apps import get_available_app_model_by_id, is_user_app_enabled
if get_app_by_id_db(app_id) is None:
raise HTTPException(status_code=404, detail='App not found')
app = get_available_app_model_by_id(app_id, uid)
if app is None:
raise HTTPException(status_code=403, detail='App is not available to this user')
if not app.works_with_memories():
raise HTTPException(status_code=400, detail='App does not support conversation summarization')
if app.disabled:
raise HTTPException(status_code=409, detail='App is currently unavailable')
if not is_user_app_enabled(uid, app_id):
raise HTTPException(status_code=409, detail='App must be enabled before it can summarize a conversation')
return app
def _ensure_aware(value: datetime) -> datetime:
# FastAPI parses a query datetime as naive or timezone-aware depending on whether the client
# included a UTC offset. Normalize to timezone-aware (UTC) so comparing the two ends of a date
# range never raises TypeError on mixed awareness (which would surface as a 500).
return value if value.tzinfo is not None else value.replace(tzinfo=timezone.utc)
# Firestore 'in' filters accept at most 30 values (see database/apps.py, database/chat.py). Reject
# an oversized status/source filter before it reaches the query so a caller cannot turn a
# comma-separated filter into an unhandled 500. ConversationStatus and the source set are both
# tiny, so a cap of 20 can never reject a request a real client would send.
MAX_IN_FILTER_VALUES = 20
LEGACY_SEGMENT_INDEX_PREFIX = '#index:'
def _reject_oversized_filter(values: List[str], field_name: str) -> None:
if len(values) > MAX_IN_FILTER_VALUES:
raise HTTPException(status_code=400, detail=f"{field_name} accepts at most {MAX_IN_FILTER_VALUES} values")
def _resolve_bulk_segment_indices(conversation: Conversation, requested_ids: List[str]) -> List[int]:
"""Resolve assignment targets before mutating any transcript segment.
Desktop sends positional targets for legacy transcripts that were stored without
segment IDs. Exact IDs remain the preferred wire contract; positional targets are
only accepted for completed conversations because an in-progress transcript can
still be reordered or merged.
"""
segments = conversation.transcript_segments
segment_indices_by_id = {segment.id: index for index, segment in enumerate(segments)}
resolved_indices: List[int] = []
unresolved_ids: List[str] = []
allow_legacy_indices = conversation.status == ConversationStatus.completed
for requested_id in requested_ids:
segment_index = segment_indices_by_id.get(requested_id)
if segment_index is None and allow_legacy_indices and requested_id.startswith(LEGACY_SEGMENT_INDEX_PREFIX):
raw_index = requested_id[len(LEGACY_SEGMENT_INDEX_PREFIX) :]
if raw_index.isascii() and raw_index.isdecimal():
candidate_index = int(raw_index)
if candidate_index < len(segments):
segment_index = candidate_index
if segment_index is None:
unresolved_ids.append(requested_id)
elif segment_index not in resolved_indices:
resolved_indices.append(segment_index)
if unresolved_ids:
raise HTTPException(
status_code=409,
detail=f'Unable to resolve transcript segment assignment target(s): {", ".join(unresolved_ids)}',
)
return resolved_indices
@router.get(
'/v1/conversations',
response_model=List[Conversation],
tags=['conversations'],
description=(
"List responses may omit detail-only fields such as transcript_segments. "
"Clients should treat omitted transcript_segments as unknown/not loaded, not as an empty transcript. "
"Large accounts can outrun the request budget; such responses return a partial "
"newest-first array with the X-Omi-List-Truncated: true header instead of a 504 (#11831)."
),
)
def get_conversations(
request: Request = None, # type: ignore[assignment]
response: Response = None, # type: ignore[assignment]
limit: PositiveLimit = 100,
offset: NonNegativeOffset = 0,
statuses: Optional[str] = "processing,completed",
include_discarded: bool = True,
sources: Optional[str] = Query(
None,
description="Comma-separated source filter (e.g. friend,omi); combine with statuses only for one source.",
),
start_date: Optional[datetime] = Query(None, description="Filter by start date (inclusive)"),
end_date: Optional[datetime] = Query(None, description="Filter by end date (inclusive)"),
folder_id: Optional[str] = Query(None, description="Filter by folder ID"),
starred: Optional[bool] = Query(None, description="Filter by starred status"),
uid: str = Depends(auth.get_current_user_uid),
):
if start_date is not None and end_date is not None and _ensure_aware(start_date) > _ensure_aware(end_date):
raise HTTPException(status_code=400, detail="start_date must be earlier than or equal to end_date")
logger.info(f'get_conversations {uid} {limit} {offset} {statuses} {sources} {folder_id} {starred}')
# force convos statuses to processing, completed on the empty filter
if len(statuses) == 0:
statuses = "processing,completed"
source_list = [source.strip() for source in sources.split(',') if source.strip()] if sources else []
if len(source_list) > 1 and len([status.strip() for status in statuses.split(',') if status.strip()]) > 1:
# Firestore permits one disjunctive `in` predicate. The archive's
# supported `sources=omi&statuses=processing,completed` path uses an
# equality source filter; reject only the unsupported two-`in` shape.
raise HTTPException(
status_code=400,
detail='multiple sources cannot be combined with multiple statuses',
)
status_filter = statuses.split(",") if len(statuses) > 0 else []
_reject_oversized_filter(status_filter, "statuses")
_reject_oversized_filter(source_list, "sources")
# Request-scoped budget: the server-side offset is charged before the
# query and the page stream runs under the derived per-RPC timeout, so a
# deep page cannot consume the whole HTTP_GET_TIMEOUT (#11831).
budget = list_read_budget_for_request(request, route='conversations')
conversations = conversations_db.get_conversations_without_photos(
uid,
limit,
offset,
include_discarded=include_discarded,
statuses=status_filter,
sources=source_list,
start_date=start_date,
end_date=end_date,
folder_id=folder_id,
starred=starred,
budget=budget,
)
redact_conversations_for_list(conversations)
if budget.truncated and response is not None:
response.headers[OMI_LIST_TRUNCATED_HEADER] = OMI_LIST_TRUNCATED_VALUE
budget.observe('truncated' if budget.truncated else 'complete')
return conversations
@router.get('/v1/conversations/count', tags=['conversations'], response_model=ConversationsCountResponse)
def get_conversations_count(
statuses: Optional[str] = Query(None, description="Comma-separated status filter (e.g. processing,completed)"),
include_discarded: bool = Query(False),
start_date: Optional[datetime] = Query(None, description="Filter by start date (inclusive)"),
end_date: Optional[datetime] = Query(None, description="Filter by end date (inclusive)"),
folder_id: Optional[str] = Query(None, description="Filter by folder ID"),
starred: Optional[bool] = Query(None, description="Filter by starred status"),
sources: Optional[str] = Query(
None,
description="Comma-separated source filter (e.g. friend,omi); combine with statuses only for one source.",
),
uid: str = Depends(auth.get_current_user_uid),
):
if start_date is not None and end_date is not None and _ensure_aware(start_date) > _ensure_aware(end_date):
raise HTTPException(status_code=400, detail="start_date must be earlier than or equal to end_date")
status_list = [s.strip() for s in statuses.split(',') if s.strip()] if statuses else []
source_list = [s.strip() for s in sources.split(',') if s.strip()] if sources else []
_reject_oversized_filter(status_list, "statuses")
_reject_oversized_filter(source_list, "sources")
if len(source_list) > 1 and len(status_list) > 1:
raise HTTPException(status_code=400, detail='multiple sources cannot be combined with multiple statuses')
count = conversations_db.get_conversations_count(
uid,
include_discarded=include_discarded,
statuses=status_list,
start_date=start_date,
end_date=end_date,
folder_id=folder_id,
starred=starred,
sources=source_list,
)
if source_list:
# Echo the filter so clients can tell this backend applied it (older
# backends ignore the unknown param and return the unfiltered total).
return {'count': count, 'sources': source_list}
return {'count': count}
@router.get(
"/v1/conversations/{conversation_id}",
response_model=Conversation,
tags=['conversations'],
description=(
"Detail responses include transcript fields when available. Locked or redacted conversations "
"may include an empty transcript_segments array even though transcript data exists."
),
)
def get_conversation_by_id(
conversation_id: str,
source: Optional[str] = Query(None, description="Optional provenance constraint for a detail read"),
include_discarded: bool = Query(True),
uid: str = Depends(auth.get_current_user_uid),
):
logger.info(f'get_conversation_by_id {uid} {conversation_id}')
conversation = _get_valid_conversation_by_id(uid, conversation_id)
if source is not None:
if source != 'omi':
raise HTTPException(
status_code=400, detail="Only source=omi is supported for provenance-constrained detail reads"
)
if conversation.get('source') != 'omi' or (not include_discarded and conversation.get('discarded', False)):
raise HTTPException(status_code=404, detail="Conversation not found")
# Lazy processing: a desktop conversation stored raw (deferred) for a freemium/Neo user is
# enriched on first open. Other conversations are returned unchanged.
if conversation.get('deferred'):
conversation = _enrich_deferred_conversation(uid, conversation)
else:
_dispatch_first_open_work(uid, conversation)
return conversation
@router.patch(
"/v1/conversations/{conversation_id}/title", tags=['conversations'], response_model=ConversationMutationResponse
)
def patch_conversation_title(conversation_id: str, title: str, uid: str = Depends(auth.get_current_user_uid)):
_get_valid_conversation_by_id(uid, conversation_id)
conversations_db.update_conversation_title(uid, conversation_id, title)
return {'status': 'Ok', 'conversation': _get_valid_conversation_by_id(uid, conversation_id)}
@router.delete(
"/v1/conversations/{conversation_id}/calendar-event",
tags=['conversations'],
response_model=ConversationStatusResponse,
)
def unlink_calendar_event(conversation_id: str, uid: str = Depends(auth.get_current_user_uid)):
"""
Unlink a calendar event from a conversation.
This removes the calendar_event field from the conversation.
"""
_get_valid_conversation_by_id(uid, conversation_id)
conversations_db.update_conversation(uid, conversation_id, {'calendar_event': None})
return {'status': 'Ok'}
class LinkCalendarEventRequest(BaseModel):
event_id: str
def _event_to_calendar_event_link(event: dict) -> Optional[CalendarEventLink]:
"""Convert a raw Google Calendar event to CalendarEventLink model."""
start_time, end_time = parse_event_times(event)