Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

feat(meetings): unify live-meeting speaker IDs with the global embedding pipeline (#3788)

Louis Beaumont20a2804ed443
diff --git a/crates/screenpipe-audio/src/audio_manager/reconciliation.rs b/crates/screenpipe-audio/src/audio_manager/reconciliation.rs
index 3c586e35a..3a470517e 100644
--- a/crates/screenpipe-audio/src/audio_manager/reconciliation.rs
+++ b/crates/screenpipe-audio/src/audio_manager/reconciliation.rs
@@ -24,6 +24,11 @@ static BACKFILL_LAST_TRIGGERED_MS: AtomicU64 = AtomicU64::new(0);
const BACKFILL_MIN_INTERVAL: Duration = Duration::from_secs(30);
const BACKFILL_MAX_CHUNKS_PER_PASS: usize = 12;
+/// Max gap between a live meeting segment's timestamp and an identified
+/// audio_transcriptions row when mapping the segment to a global speaker_id.
+/// The mirrored live row shares the segment's exact timestamp, so this only
+/// needs slack for clock jitter.
+const MEETING_SEGMENT_SPEAKER_WINDOW_SECS: f64 = 15.0;
const RECONCILIATION_LOOKBACK_HOURS: i64 = 24 * 7;
const RECONCILIATION_FRESHNESS_DELAY_SECS: i64 = 10 * 60;
const RECONCILIATION_CHUNKS_PER_SWEEP: i64 = 50;
@@ -544,6 +549,28 @@ pub async fn reconcile_untranscribed(
backfilled
);
}
+
+ // Map live meeting-transcript segments onto the global speaker ids the
+ // chunk backfill just resolved (reuses the same identities — no second
+ // embedding path). Pure DB; the mirrored live row shares each segment's
+ // timestamp so it matches first.
+ match db
+ .backfill_meeting_segment_speakers(
+ chrono::Utc::now() - chrono::Duration::hours(24),
+ MEETING_SEGMENT_SPEAKER_WINDOW_SECS,
+ )
+ .await
+ {
+ Ok(n) if n > 0 => info!(
+ "reconciliation: mapped {} live meeting segment(s) to global speaker ids",
+ n
+ ),
+ Ok(_) => {}
+ Err(e) => warn!(
+ "reconciliation: meeting-segment speaker mapping failed: {}",
+ e
+ ),
+ }
}
success_count
diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rs
index a2642f637..6bd89ee65 100644
--- a/crates/screenpipe-db/src/db.rs
+++ b/crates/screenpipe-db/src/db.rs
@@ -9051,9 +9051,12 @@ LIMIT ? OFFSET ?
let max_ts = segs.iter().map(|s| s.captured_at).max().unwrap() + window;
// Candidate chunks across the meeting window, fetched ONCE (a 40-min meeting
- // is ~80 chunks), then matched in memory — avoids a per-segment query.
+ // is ~80 chunks), then matched in memory — avoids a per-segment query. We
+ // pull file_path because chunk audio is single-device and the device is
+ // encoded in the filename ("<name> (input|output)_<ts>.mp4"), which is the
+ // only place a chunk records its device.
let chunk_rows = sqlx::query(
- "SELECT id, timestamp FROM audio_chunks \
+ "SELECT id, timestamp, file_path FROM audio_chunks \
WHERE timestamp IS NOT NULL \
AND julianday(timestamp) >= julianday(?1) \
AND julianday(timestamp) <= julianday(?2)",
@@ -9063,12 +9066,15 @@ LIMIT ? OFFSET ?
.fetch_all(&self.pool)
.await?;
- let chunks: Vec<(i64, i64)> = chunk_rows
+ let chunks: Vec<(i64, i64, String)> = chunk_rows
.iter()
.filter_map(|r| {
let id: i64 = r.try_get("id").ok()?;
let ts: DateTime<Utc> = r.try_get("timestamp").ok()?;
- Some((id, ts.timestamp_millis()))
+ // Lowercased for case-insensitive device matching (mirrors #3776's
+ // lower(file_path) in mark_chunks_covered_by_live).
+ let file_path: String = r.try_get::<String, _>("file_path").unwrap_or_default();
+ Some((id, ts.timestamp_millis(), file_path.to_lowercase()))
})
.collect();
if chunks.is_empty() {
@@ -9080,13 +9086,33 @@ LIMIT ? OFFSET ?
let mut inserted: u64 = 0;
for s in &segs {
let seg_ms = s.captured_at.timestamp_millis();
- let Some(&(chunk_id, chunk_ms)) = chunks.iter().min_by_key(|c| (c.1 - seg_ms).abs())
- else {
+ // Match the SAME physical device's chunk so an input (mic) segment can't
+ // inherit a remote speaker from a System Audio (output) chunk, and vice
+ // versa. The device string is sanitized the same way the recorder names
+ // files (only '/' and '\\' replaced). Fall back to nearest-any within the
+ // window if no same-device chunk exists (legacy/odd naming) — never worse
+ // than before.
+ let device_key = format!(
+ "{} ({})",
+ s.device_name,
+ if s.is_input { "input" } else { "output" }
+ )
+ .replace(['/', '\\'], "_")
+ .to_lowercase();
+ let pick = chunks
+ .iter()
+ .filter(|c| (c.1 - seg_ms).abs() <= window_ms && c.2.contains(device_key.as_str()))
+ .min_by_key(|c| (c.1 - seg_ms).abs())
+ .or_else(|| {
+ chunks
+ .iter()
+ .filter(|c| (c.1 - seg_ms).abs() <= window_ms)
+ .min_by_key(|c| (c.1 - seg_ms).abs())
+ });
+ let Some(chunk) = pick else {
continue;
};
- if (chunk_ms - seg_ms).abs() > window_ms {
- continue;
- }
+ let chunk_id = chunk.0;
let text_length = s.transcript.len() as i64;
let res = sqlx::query(
"INSERT OR IGNORE INTO audio_transcriptions \
@@ -9108,6 +9134,81 @@ LIMIT ? OFFSET ?
Ok(inserted)
}
+ /// Give live meeting-transcript segments the SAME global `speaker_id` that the
+ /// engine-agnostic backfill (`backfill_missing_speakers`) resolved on
+ /// `audio_transcriptions` — so the Meeting view shows the cross-meeting, nameable
+ /// identity instead of Deepgram's per-stream "speaker N" label.
+ ///
+ /// For each segment still missing a speaker (and `captured_at >= since`), take the
+ /// `speaker_id` of the nearest already-identified `audio_transcriptions` row within
+ /// `coverage_window_secs`. The mirrored live row shares the segment's exact
+ /// timestamp, so once the chunk backfill stamps it, it matches first. Idempotent —
+ /// only fills NULLs, and the `EXISTS` guard avoids no-op NULL writes. Returns rows
+ /// updated. Cheap: runs on the reconciliation sweep, never the hot path.
+ pub async fn backfill_meeting_segment_speakers(
+ &self,
+ since: DateTime<Utc>,
+ coverage_window_secs: f64,
+ ) -> Result<u64, SqlxError> {
+ // SQLite can't correlate the UPDATE target table inside a SET subquery, so
+ // do it as fetch-candidates → per-row nearest-lookup → update-by-id (the
+ // same shape as the mirror). Capped per pass; resolved segments drop out of
+ // the candidate set, so steady-state work is just newly-mirrored segments.
+ const PER_PASS_LIMIT: i64 = 500;
+ let window_days = coverage_window_secs / 86_400.0;
+
+ let segs = sqlx::query(
+ "SELECT id, captured_at, device_type FROM meeting_transcript_segments \
+ WHERE speaker_id IS NULL AND julianday(captured_at) >= julianday(?1) \
+ ORDER BY captured_at DESC LIMIT ?2",
+ )
+ .bind(since)
+ .bind(PER_PASS_LIMIT)
+ .fetch_all(&self.pool)
+ .await?;
+ if segs.is_empty() {
+ return Ok(0);
+ }
+
+ let mut tx = self.begin_immediate_with_retry().await?;
+ let mut updated: u64 = 0;
+ for seg in &segs {
+ let seg_id: i64 = seg.get("id");
+ let captured_at: DateTime<Utc> = seg.get("captured_at");
+ let is_input: bool =
+ seg.try_get::<String, _>("device_type").unwrap_or_default() == "input";
+ // The global speaker_id of the nearest already-identified audio row OF
+ // THE SAME DEVICE (input vs output), so a mic segment can't pick up a
+ // remote speaker. The mirrored live row shares this exact timestamp +
+ // device, so it wins.
+ let speaker_id: Option<i64> = sqlx::query_scalar(
+ "SELECT at.speaker_id FROM audio_transcriptions at \
+ WHERE at.speaker_id IS NOT NULL \
+ AND COALESCE(at.is_input_device, 1) = ?3 \
+ AND ABS(julianday(at.timestamp) - julianday(?1)) <= ?2 \
+ ORDER BY ABS(julianday(at.timestamp) - julianday(?1)) ASC LIMIT 1",
+ )
+ .bind(captured_at)
+ .bind(window_days)
+ .bind(is_input)
+ .fetch_optional(&mut **tx.conn())
+ .await?;
+ if let Some(sid) = speaker_id {
+ let r = sqlx::query(
+ "UPDATE meeting_transcript_segments SET speaker_id = ?1 \
+ WHERE id = ?2 AND speaker_id IS NULL",
+ )
+ .bind(sid)
+ .bind(seg_id)
+ .execute(&mut **tx.conn())
+ .await?;
+ updated += r.rows_affected();
+ }
+ }
+ tx.commit().await?;
+ Ok(updated)
+ }
+
pub async fn list_meeting_transcript_segments(
&self,
meeting_id: i64,
@@ -9127,24 +9228,28 @@ LIMIT ? OFFSET ?
),
live_segments AS (
SELECT
- id,
- meeting_id,
+ mts.id,
+ mts.meeting_id,
'live' AS source,
- provider,
- model,
- item_id,
- device_name,
- device_type,
+ mts.provider,
+ mts.model,
+ mts.item_id,
+ mts.device_name,
+ mts.device_type,
NULL AS audio_transcription_id,
NULL AS audio_chunk_id,
NULL AS audio_file_path,
- NULL AS speaker_id,
- speaker_name,
- transcript,
- captured_at,
- created_at
- FROM meeting_transcript_segments
- WHERE meeting_id = ?1
+ mts.speaker_id AS speaker_id,
+ -- Prefer the resolved global speaker's name; fall back to the
+ -- free-text Deepgram label until backfilled / if the speaker is
+ -- unnamed (NULLIF treats '' as "no name yet").
+ COALESCE(NULLIF(s.name, ''), mts.speaker_name) AS speaker_name,
+ mts.transcript,
+ mts.captured_at,
+ mts.created_at
+ FROM meeting_transcript_segments mts
+ LEFT JOIN speakers s ON s.id = mts.speaker_id
+ WHERE mts.meeting_id = ?1
),
background_segments AS (
SELECT
diff --git a/crates/screenpipe-db/src/migrations/20260603120000_meeting_transcript_speaker_id.sql b/crates/screenpipe-db/src/migrations/20260603120000_meeting_transcript_speaker_id.sql
new file mode 100644
index 000000000..018f33a7b
--- /dev/null
+++ b/crates/screenpipe-db/src/migrations/20260603120000_meeting_transcript_speaker_id.sql
@@ -0,0 +1,11 @@
+-- Add a global speaker_id to live meeting transcript segments so the Meeting view
+-- can show the same embedding-matched, cross-meeting speaker identity that the
+-- timeline/search already get via audio_transcriptions.speaker_id. Populated
+-- post-hoc by DatabaseManager::backfill_meeting_segment_speakers (no FK, matching
+-- audio_transcriptions.speaker_id which is also unconstrained; orphans are cleaned
+-- up the same way). NULL until resolved → callers fall back to the free-text
+-- speaker_name from Deepgram diarization.
+ALTER TABLE meeting_transcript_segments ADD COLUMN speaker_id INTEGER;
+
+CREATE INDEX IF NOT EXISTS idx_meeting_transcript_segments_speaker
+ ON meeting_transcript_segments(speaker_id);
diff --git a/crates/screenpipe-db/tests/timeline_live_meeting_test.rs b/crates/screenpipe-db/tests/timeline_live_meeting_test.rs
index b56804c1d..fe035a28a 100644
--- a/crates/screenpipe-db/tests/timeline_live_meeting_test.rs
+++ b/crates/screenpipe-db/tests/timeline_live_meeting_test.rs
@@ -333,4 +333,190 @@ mod timeline_live_meeting_tests {
"mirrored segment must appear on the timeline exactly once (mirror shown, live row deduped)"
);
}
+
+ /// Once the engine-agnostic backfill has resolved a global `speaker_id` on the
+ /// covering audio (here pre-seeded), `backfill_meeting_segment_speakers` maps the
+ /// live segment onto it, and the Meeting view shows the global speaker's NAME
+ /// instead of Deepgram's free-text "speaker N".
+ #[tokio::test]
+ async fn test_meeting_segment_speaker_backfill_resolves_global_id() {
+ let db = setup_test_db().await;
+ let base = Utc::now();
+
+ // A named global speaker (as the embedding backfill would have created/named).
+ let speaker = db.create_speaker_with_name("Chris Ng").await.unwrap();
+
+ // The meeting's covering audio, already identified with that speaker.
+ let chunk_id = db
+ .insert_audio_chunk("meeting.mp4", Some(base))
+ .await
+ .unwrap();
+ db.insert_audio_transcription(
+ chunk_id,
+ "identified background line",
+ 0,
+ "",
+ &AudioDevice {
+ name: "System Audio".to_string(),
+ device_type: DeviceType::Output,
+ },
+ Some(speaker.id),
+ None,
+ None,
+ Some(base),
+ )
+ .await
+ .unwrap();
+
+ // A live segment at the same time, still on Deepgram's free-text label.
+ let meeting_id = db
+ .insert_meeting("zoom.us", "ui_scan", None, None)
+ .await
+ .unwrap();
+ db.insert_meeting_transcript_segment(
+ meeting_id,
+ "screenpipe-cloud",
+ Some("nova-3"),
+ "deepgram:0:0",
+ "System Audio",
+ "output",
+ Some("speaker 1"),
+ "audience question",
+ base + Duration::seconds(1),
+ )
+ .await
+ .unwrap();
+
+ let mapped = db
+ .backfill_meeting_segment_speakers(base - Duration::hours(1), 15.0)
+ .await
+ .unwrap();
+ assert_eq!(
+ mapped, 1,
+ "the live segment should map to the global speaker"
+ );
+
+ let segs = db
+ .list_meeting_transcript_segments(meeting_id)
+ .await
+ .unwrap();
+ let live = segs
+ .iter()
+ .find(|s| s.source == "live")
+ .expect("live segment present");
+ assert_eq!(live.speaker_id, Some(speaker.id));
+ assert_eq!(
+ live.speaker_name.as_deref(),
+ Some("Chris Ng"),
+ "Meeting view shows the resolved global name, not the Deepgram label"
+ );
+ }
+
+ /// Until a segment is resolved, the Meeting view falls back to Deepgram's
+ /// free-text `speaker_name`, and the backfill maps nothing.
+ #[tokio::test]
+ async fn test_meeting_segment_falls_back_to_freetext_speaker() {
+ let db = setup_test_db().await;
+ let base = Utc::now();
+
+ let meeting_id = db
+ .insert_meeting("zoom.us", "ui_scan", None, None)
+ .await
+ .unwrap();
+ db.insert_meeting_transcript_segment(
+ meeting_id,
+ "screenpipe-cloud",
+ None,
+ "deepgram:0:0",
+ "System Audio",
+ "output",
+ Some("speaker 2"),
+ "unresolved line",
+ base,
+ )
+ .await
+ .unwrap();
+
+ // No identified audio → nothing to map.
+ let mapped = db
+ .backfill_meeting_segment_speakers(base - Duration::hours(1), 15.0)
+ .await
+ .unwrap();
+ assert_eq!(mapped, 0);
+
+ let segs = db
+ .list_meeting_transcript_segments(meeting_id)
+ .await
+ .unwrap();
+ let live = segs
+ .iter()
+ .find(|s| s.source == "live")
+ .expect("live segment present");
+ assert_eq!(live.speaker_id, None);
+ assert_eq!(
+ live.speaker_name.as_deref(),
+ Some("speaker 2"),
+ "falls back to the free-text Deepgram label when unresolved"
+ );
+ }
+
+ /// The mirror must attach a segment to a chunk of the SAME device, even when a
+ /// different-device chunk is nearer in time — otherwise a mic (input) segment
+ /// would inherit a remote speaker from a System Audio (output) chunk. Device is
+ /// matched via the filename, the only place a chunk records it.
+ #[tokio::test]
+ async fn test_mirror_associates_segment_to_same_device_chunk() {
+ let db = setup_test_db().await;
+ let base = Utc::now();
+
+ // OUTPUT chunk exactly at `base` (nearest), INPUT chunk 2s away.
+ let out_chunk = db
+ .insert_audio_chunk("System Audio (output)_t.mp4", Some(base))
+ .await
+ .unwrap();
+ let in_chunk = db
+ .insert_audio_chunk(
+ "Built-in Mic (input)_t.mp4",
+ Some(base + Duration::seconds(2)),
+ )
+ .await
+ .unwrap();
+
+ // An INPUT (mic) segment at `base` — naively it would grab the nearer OUTPUT chunk.
+ let meeting_id = db
+ .insert_meeting("zoom.us", "ui_scan", None, None)
+ .await
+ .unwrap();
+ db.insert_meeting_transcript_segment(
+ meeting_id,
+ "screenpipe-cloud",
+ None,
+ "deepgram:0:0",
+ "Built-in Mic",
+ "input",
+ Some("speaker 1"),
+ "my own words",
+ base,
+ )
+ .await
+ .unwrap();
+
+ let n = db
+ .mirror_live_meeting_to_audio_transcriptions(meeting_id, 15.0)
+ .await
+ .unwrap();
+ assert_eq!(n, 1);
+
+ let chunk_id: i64 = sqlx::query_scalar(
+ "SELECT audio_chunk_id FROM audio_transcriptions WHERE transcription = 'my own words'",
+ )
+ .fetch_one(&db.pool)
+ .await
+ .unwrap();
+ assert_eq!(
+ chunk_id, in_chunk,
+ "input segment must map to the input-device chunk, not the nearer output chunk"
+ );
+ assert_ne!(chunk_id, out_chunk);
+ }
}