Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(call): adjust transcript/recording times to reduce delay in playback sync (#3003)
Will Hutchinsonbad2aa5d7e6e
diff --git a/agents/transcription/transcriber.py b/agents/transcription/transcriber.pyindex 8e73e1ba15..66a25fc30a 100644--- a/agents/transcription/transcriber.py+++ b/agents/transcription/transcriber.py@@ -70,12 +70,20 @@ class Transcriber(Agent):# Word counts per Deepgram speaker int, accumulated across final# transcripts inside a single user turn and cleared on turn completion.self._pending_speakers: Counter[int] = Counter()- # Earliest speech-start and latest speech-end wall clocks observed- # across FINAL transcripts within the current turn. Derived from- # Deepgram word-level timing so segments line up with the audio- # rather than the end-of-turn callback.- self._pending_started_at: datetime | None = None- self._pending_ended_at: datetime | None = None+ # Wall-clock estimate of the STT stream's t=0 (the moment Deepgram+ # began consuming this participant's audio). Each FINAL gives us+ # an upper bound — `now() - words[-1].end_time` is at most+ # `true_t0 + final_delivery_lag` — so the MIN across FINALs+ # converges to the true value. Used to translate Deepgram's+ # stream-relative word offsets into absolute UTC for segment+ # timestamps and to anchor the recording timeline on the server.+ self._stream_t0_wall: datetime | None = None+ # Min/max Deepgram-stream-relative word offsets (seconds) seen+ # across FINALs within the current turn. Combined with+ # `_stream_t0_wall` these give started_at/ended_at without baking+ # in FINAL-delivery lag.+ self._pending_first_word_offset: float | None = None+ self._pending_last_word_offset: float | None = None# Deepgram's speaker ints are only unique within one streaming session.# Namespace them with a nonce regenerated per Transcriber so a reconnect# doesn't silently merge two different humans under the same UUID.@@ -102,24 +110,32 @@ class Transcriber(Agent):alt = event.alternatives[0] if event.alternatives else Nonewords = list(getattr(alt, "words", None) or ())if words:- # Deepgram word.start/end are seconds relative to the STT- # stream start; we don't expose that anchor here. Pin- # speech_end to "now" (FINAL arrives ~immediately after- # speech ends + endpointing) and back-calculate the start- # from the word-span duration.- speech_end = datetime.now(timezone.utc)- span = max(words[-1].end_time - words[0].start_time, 0.0)- speech_start = speech_end - timedelta(seconds=span)+ first_offset = words[0].start_time+ last_offset = words[-1].end_time++ # Refine stream-t0 estimate. `now() - last_word.end_time`+ # bounds true_t0 from above (because now() arrives at+ # least final_delivery_lag after the last word ended);+ # the MIN across FINALs is our best estimate.+ implied_t0 = datetime.now(timezone.utc) - timedelta(+ seconds=last_offset+ )+ if (+ self._stream_t0_wall is None+ or implied_t0 < self._stream_t0_wall+ ):+ self._stream_t0_wall = implied_t0+if (- self._pending_started_at is None- or speech_start < self._pending_started_at+ self._pending_first_word_offset is None+ or first_offset < self._pending_first_word_offset):- self._pending_started_at = speech_start+ self._pending_first_word_offset = first_offsetif (- self._pending_ended_at is None- or speech_end > self._pending_ended_at+ self._pending_last_word_offset is None+ or last_offset > self._pending_last_word_offset):- self._pending_ended_at = speech_end+ self._pending_last_word_offset = last_offsetfor word in words:speaker = getattr(word, "speaker", None)@@ -133,12 +149,32 @@ class Transcriber(Agent):self, chat_ctx: llm.ChatContext, new_message: llm.ChatMessage):content = new_message.text_content+ # Snapshot pending state and clear unconditionally so an empty-content+ # turn (e.g. VAD ended a turn with no final text) can't leak word+ # offsets or speaker counts into the next turn's accumulators.+ first_word_offset = self._pending_first_word_offset+ last_word_offset = self._pending_last_word_offset+ pending_speakers = self._pending_speakers+ self._pending_first_word_offset = None+ self._pending_last_word_offset = None+ self._pending_speakers = Counter()+if content:now = datetime.now(timezone.utc)- started_at = self._pending_started_at or now- ended_at = self._pending_ended_at or now- self._pending_started_at = None- self._pending_ended_at = None+ if (+ self._stream_t0_wall is not None+ and first_word_offset is not None+ and last_word_offset is not None+ ):+ started_at = self._stream_t0_wall + timedelta(+ seconds=first_word_offset+ )+ ended_at = self._stream_t0_wall + timedelta(+ seconds=last_word_offset+ )+ else:+ started_at = now+ ended_at = nowextra = new_message.extra if isinstance(new_message.extra, dict) else {}source_id = (@@ -153,10 +189,9 @@ class Transcriber(Agent):segment_id = str(uuid.uuid5(uuid.NAMESPACE_URL, segment_seed))diarized_speaker_id = None- if self._pending_speakers:- dominant_speaker, _ = self._pending_speakers.most_common(1)[0]+ if pending_speakers:+ dominant_speaker, _ = pending_speakers.most_common(1)[0]diarized_speaker_id = self._resolve_diarized_speaker_id(dominant_speaker)- self._pending_speakers.clear()segment = {"segmentId": segment_id,@@ -165,6 +200,15 @@ class Transcriber(Agent):"content": content,"startedAt": started_at.isoformat(),"endedAt": ended_at.isoformat(),+ # Sent so the server can anchor `recording_started_at` to+ # the earliest first-audio-frame instant across participants+ # rather than the egress webhook envelope time (which fires+ # before any audio is captured).+ "streamStartedAt": (+ self._stream_t0_wall.isoformat()+ if self._stream_t0_wall is not None+ else None+ ),"isFinal": True,}max_attempts = 3diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.tsindex f0892c6320..936d544692 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts@@ -655,6 +655,7 @@ export * from './threadUpdatedAt';export * from './transcriptSegmentRequest';export * from './transcriptSegmentRequestDiarizedSpeakerId';export * from './transcriptSegmentRequestEndedAt';+export * from './transcriptSegmentRequestStreamStartedAt';export * from './typedSuccessResponse';export * from './typedSuccessResponseDataOneOf';export * from './unthreadedPdfUuidRequest';diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequest.tsindex 4e41362344..a11c44735e 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequest.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequest.ts@@ -6,6 +6,7 @@*/import type { TranscriptSegmentRequestDiarizedSpeakerId } from './transcriptSegmentRequestDiarizedSpeakerId';import type { TranscriptSegmentRequestEndedAt } from './transcriptSegmentRequestEndedAt';+import type { TranscriptSegmentRequestStreamStartedAt } from './transcriptSegmentRequestStreamStartedAt';/*** A transcript segment from LiveKit Inference STT.@@ -27,4 +28,10 @@ tracks in a call. `None` when the provider didn't return a speaker label. */speakerId: string;/** When the speaker started talking for this segment. */startedAt: string;+ /** Wall-clock when the transcriber's STT stream first received audio+for this participant. The server takes the earliest non-null value+across all participants and uses it to overwrite the+`egress_started`-derived `recording_started_at`, which is too early+(it stamps egress bootstrap, not first audio frame). */+ streamStartedAt?: TranscriptSegmentRequestStreamStartedAt;}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequestStreamStartedAt.ts b/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequestStreamStartedAt.tsnew file mode 100644index 0000000000..1d34a834f2--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequestStreamStartedAt.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Wall-clock when the transcriber's STT stream first received audio+for this participant. The server takes the earliest non-null value+across all participants and uses it to overwrite the+`egress_started`-derived `recording_started_at`, which is too early+(it stamps egress bootstrap, not first audio frame).+ */+export type TranscriptSegmentRequestStreamStartedAt = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex d77587917a..875f7da667 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -1210,6 +1210,12 @@ export const ingestTranscriptBody = zodstartedAt: zod.iso.datetime({}).describe('When the speaker started talking for this segment.'),+ streamStartedAt: zod.iso+ .datetime({})+ .nullish()+ .describe(+ "Wall-clock when the transcriber's STT stream first received audio\nfor this participant. The server takes the earliest non-null value\nacross all participants and uses it to overwrite the\n`egress_started`-derived `recording_started_at`, which is too early\n(it stamps egress bootstrap, not first audio frame)."+ ),}).describe('A transcript segment from LiveKit Inference STT.');diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 84b805cd2a..4624377b8b 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -11992,6 +11992,11 @@"type": "string","format": "date-time","description": "When the speaker started talking for this segment."+ },+ "streamStartedAt": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "Wall-clock when the transcriber's STT stream first received audio\nfor this participant. The server takes the earliest non-null value\nacross all participants and uses it to overwrite the\n`egress_started`-derived `recording_started_at`, which is too early\n(it stamps egress bootstrap, not first audio frame)."}}},diff --git a/rust/cloud-storage/.sqlx/query-c370c41d4e1fd496016a5689da4ca6dd9e6af7a364499871944691b3dfee5a09.json b/rust/cloud-storage/.sqlx/query-c370c41d4e1fd496016a5689da4ca6dd9e6af7a364499871944691b3dfee5a09.jsonnew file mode 100644index 0000000000..f8ee410a86--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-c370c41d4e1fd496016a5689da4ca6dd9e6af7a364499871944691b3dfee5a09.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calls\n SET recording_started_at = $1\n WHERE id = $2\n AND (\n recording_started_at IS NULL\n OR recording_started_at = date_trunc('second', recording_started_at)\n OR $1 < recording_started_at\n )\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Timestamptz",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "c370c41d4e1fd496016a5689da4ca6dd9e6af7a364499871944691b3dfee5a09"+}diff --git a/rust/cloud-storage/.sqlx/query-f740b3f09ab349c876e1c7d8e42ad59600be3ea7f6f3db61fcc3045330a20f39.json b/rust/cloud-storage/.sqlx/query-f740b3f09ab349c876e1c7d8e42ad59600be3ea7f6f3db61fcc3045330a20f39.jsonnew file mode 100644index 0000000000..182393ae7b--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-f740b3f09ab349c876e1c7d8e42ad59600be3ea7f6f3db61fcc3045330a20f39.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE call_records\n SET recording_started_at = $1\n WHERE id = $2\n AND (\n recording_started_at IS NULL\n OR recording_started_at = date_trunc('second', recording_started_at)\n OR $1 < recording_started_at\n )\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Timestamptz",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "f740b3f09ab349c876e1c7d8e42ad59600be3ea7f6f3db61fcc3045330a20f39"+}diff --git a/rust/cloud-storage/call/src/domain/models.rs b/rust/cloud-storage/call/src/domain/models.rsindex 4ecfc0d246..a42e8d7b88 100644--- a/rust/cloud-storage/call/src/domain/models.rs+++ b/rust/cloud-storage/call/src/domain/models.rs@@ -142,6 +142,13 @@ pub struct TranscriptSegmentRequest {pub ended_at: Option<DateTime<Utc>>,/// Whether this is a final transcription (not interim).pub is_final: bool,+ /// Wall-clock when the transcriber's STT stream first received audio+ /// for this participant. The server takes the earliest non-null value+ /// across all participants and uses it to overwrite the+ /// `egress_started`-derived `recording_started_at`, which is too early+ /// (it stamps egress bootstrap, not first audio frame).+ #[serde(default)]+ pub stream_started_at: Option<DateTime<Utc>>,}/// Edit call requestdiff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo.rsindex d5a90f39ea..527ee2f4db 100644--- a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo.rs@@ -687,6 +687,59 @@ impl CallRepository for PgCallRepo {).execute(&self.pool).await?;++ // The agent's first-audio-frame wall-clock is a more accurate+ // recording-timeline anchor than the `egress_started` webhook's+ // envelope time (which fires when egress bootstraps, ~seconds+ // before any audio frame is encoded). Overwrite the column when:+ // - it's still NULL (no webhook yet), OR+ // - the existing value is at exact second precision (i.e., from+ // the webhook, which stores `from_timestamp(secs, 0)`), OR+ // - the new value is earlier than the existing agent value+ // (across multiple participants, take the earliest first-audio).+ if let Some(stream_started_at) = segment.stream_started_at {+ let active = sqlx::query!(+ r#"+ UPDATE calls+ SET recording_started_at = $1+ WHERE id = $2+ AND (+ recording_started_at IS NULL+ OR recording_started_at = date_trunc('second', recording_started_at)+ OR $1 < recording_started_at+ )+ "#,+ stream_started_at,+ call_id,+ )+ .execute(&self.pool)+ .await?;++ // Race fallback: if `archive_call` moved the row to `call_records`+ // between transcript-ingest's lookup and now, the active UPDATE+ // affects 0 rows. Apply the same conditional update to the+ // archived row (same id is reused on archive). Mirrors+ // `set_recording_started_at_by_egress_id`.+ if active.rows_affected() == 0 {+ sqlx::query!(+ r#"+ UPDATE call_records+ SET recording_started_at = $1+ WHERE id = $2+ AND (+ recording_started_at IS NULL+ OR recording_started_at = date_trunc('second', recording_started_at)+ OR $1 < recording_started_at+ )+ "#,+ stream_started_at,+ call_id,+ )+ .execute(&self.pool)+ .await?;+ }+ }+Ok(())}diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rsindex 0b560ff6b9..c58ea6310d 100644--- a/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs@@ -694,6 +694,7 @@ async fn create_transcript_segment_stores_and_increments_sequence(started_at: now,ended_at: Some(now),is_final: true,+ stream_started_at: None,};let seg2 = TranscriptSegmentRequest {segment_id: "seg-002".to_string(),@@ -703,6 +704,7 @@ async fn create_transcript_segment_stores_and_increments_sequence(started_at: now,ended_at: Some(now),is_final: true,+ stream_started_at: None,};repo.create_transcript_segment(&CALL1, &seg1).await?;@@ -752,6 +754,7 @@ async fn archive_call_copies_transcripts(pool: Pool<Postgres>) -> anyhow::Resultstarted_at: now,ended_at: Some(now),is_final: true,+ stream_started_at: None,};repo.create_transcript_segment(&CALL1, &seg).await?;@@ -812,6 +815,7 @@ async fn get_call_record_returns_active_call(pool: Pool<Postgres>) -> anyhow::Restarted_at: now,ended_at: Some(now),is_final: true,+ stream_started_at: None,},).await?;@@ -825,6 +829,7 @@ async fn get_call_record_returns_active_call(pool: Pool<Postgres>) -> anyhow::Restarted_at: now,ended_at: Some(now),is_final: true,+ stream_started_at: None,},).await?;