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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix(meetings): bind a calendar event to exactly one meeting (#6215)
Louis Beaumont019d9811f1c8
diff --git a/COVERAGE.md b/COVERAGE.mdindex 33b0cf64f..b9b9a9296 100644--- a/COVERAGE.md+++ b/COVERAGE.md@@ -32,15 +32,15 @@ results and `cargo llvm-cov` data on top when judging release confidence.- Mapped suites: 32- Mapped Rust files: 321-- Active test blocks: 3071+- Active test blocks: 3082- Ignored/manual test blocks: 137-- Weighted coverage points: 2528.1+- Weighted coverage points: 2538.8| Platform | Suites | Active tests | Ignored tests | Weighted points | Layers | Flows | Critical score || --- | --- | --- | --- | --- | --- | --- | --- |-| windows | 29 | 2940 | 132 | 2468.1 | 21 | 11 | 100% |-| macos | 29 | 2993 | 112 | 2478.5 | 22 | 11 | 100% |-| linux | 25 | 2626 | 105 | 2184.9 | 20 | 11 | 100% |+| windows | 29 | 2951 | 132 | 2478.8 | 21 | 11 | 100% |+| macos | 29 | 3004 | 112 | 2489.2 | 22 | 11 | 100% |+| linux | 25 | 2627 | 105 | 2185.6 | 20 | 11 | 100% |## Refreshdiff --git a/apps/screenpipe-app-tauri/app/(main)/home/page.tsx b/apps/screenpipe-app-tauri/app/(main)/home/page.tsxindex 38e9b247a..605e915c8 100644--- a/apps/screenpipe-app-tauri/app/(main)/home/page.tsx+++ b/apps/screenpipe-app-tauri/app/(main)/home/page.tsx@@ -743,7 +743,7 @@ function HomeContent() {};}, []);- const toggleMeeting = useCallback(async (seed?: { title?: string; attendees?: string; resumeMeetingId?: number }) => {+ const toggleMeeting = useCallback(async (seed?: { title?: string; attendees?: string; resumeMeetingId?: number; calendarEventId?: string }) => {setMeetingLoading(true);try {if (meetingState.active) {@@ -801,6 +801,9 @@ function HomeContent() {if (seed?.resumeMeetingId) body.id = seed.resumeMeetingId;if (seed?.title) body.title = seed.title;if (seed?.attendees) body.attendees = seed.attendees;+ // Claim the event so it cannot also name a later meeting.+ if (seed?.calendarEventId)+ body.calendar_event_id = seed.calendarEventId;const res = await localFetch("/meetings/start", {method: "POST",headers: { "Content-Type": "application/json" },diff --git a/apps/screenpipe-app-tauri/components/meeting-notes/index.tsx b/apps/screenpipe-app-tauri/components/meeting-notes/index.tsxindex 4b7e6c28a..4ed81477c 100644--- a/apps/screenpipe-app-tauri/components/meeting-notes/index.tsx+++ b/apps/screenpipe-app-tauri/components/meeting-notes/index.tsx@@ -23,6 +23,7 @@ import type { MeetingStatusResponse } from "@/lib/utils/meeting-state";import type { MeetingRecord } from "@/lib/utils/meeting-format";import {attendeesToString,+ calendarBindingKey,fetchUpcomingCalendarEvents,fetchUpcomingCalendarSnapshot,findOverlappingEvent,@@ -45,6 +46,7 @@ interface MeetingNotesSectionProps {title?: string;attendees?: string;resumeMeetingId?: number;+ calendarEventId?: string;}) => Promise<MeetingRecord | void> | MeetingRecord | void;captureDevices?: LiveCaptureDevice[];onCaptureDevicesRefresh?: () => void | Promise<void>;@@ -408,9 +410,13 @@ export function MeetingNotesSection({: meeting.attendees || "",};try {+ // The server claims the event for this meeting before applying these+ // fields. If another meeting already owns it, they are dropped — one+ // calendar event describes one meeting.const body: Record<string, string> = {title: next.title,attendees: next.attendees,+ calendar_event_id: calendarBindingKey(overlap),};const res = await localFetch(`/meetings/${meeting.id}`, {method: "PUT",@@ -418,13 +424,19 @@ export function MeetingNotesSection({body: JSON.stringify(body),});if (res.ok) {+ // Take the row the server actually stored — it drops the calendar+ // fields when another meeting already owns this event.+ const saved = (await res.json()) as {+ title?: string | null;+ attendees?: string | null;+ };setMeetings((prev) =>prev.map((m) =>m.id === meeting.id? {...m,- title: next.title || null,- attendees: next.attendees || null,+ title: saved.title ?? null,+ attendees: saved.attendees ?? null,}: m,),@@ -437,7 +449,11 @@ export function MeetingNotesSection({}, [meetings, meetingState.activeMeetingId]);const handleStart = useCallback(- async (seed?: { title?: string; attendees?: string }) => {+ async (seed?: {+ title?: string;+ attendees?: string;+ calendarEventId?: string;+ }) => {if (meetingState.active) return;intendingToFocusRef.current = true;try {@@ -488,6 +504,7 @@ export function MeetingNotesSection({await handleStart({title: event.title,attendees: attendeesToString(event.attendees),+ calendarEventId: calendarBindingKey(event),});},[handleStart],diff --git a/apps/screenpipe-app-tauri/lib/utils/calendar.test.ts b/apps/screenpipe-app-tauri/lib/utils/calendar.test.tsindex e7ee87100..6c0924e41 100644--- a/apps/screenpipe-app-tauri/lib/utils/calendar.test.ts+++ b/apps/screenpipe-app-tauri/lib/utils/calendar.test.ts@@ -374,3 +374,63 @@ describe("fetchUpcomingCalendarSnapshot", () => {expect(snapshot.events).toEqual([]);});});++describe("calendarBindingKey", () => {+ it("uses the provider id when the feed supplies one", async () => {+ const { calendarBindingKey } = await import("./calendar");+ expect(+ calendarBindingKey({+ id: "abc123",+ title: "Standup",+ start: "2026-08-13T18:30:00Z",+ end: "2026-08-13T19:00:00Z",+ }),+ ).toBe("abc123");+ });++ it("falls back to the event's natural identity, matching the Rust detector", async () => {+ const { calendarBindingKey } = await import("./calendar");+ const event = {+ title: "Weekly review",+ start: "2026-08-13T18:30:00Z",+ end: "2026-08-13T19:00:00Z",+ };+ // Same shape the detector builds: `title|startMs|endMs`.+ expect(calendarBindingKey(event)).toBe(+ `Weekly review|${Date.parse(event.start)}|${Date.parse(event.end)}`,+ );+ expect(calendarBindingKey({ ...event, id: "" })).toBe(+ calendarBindingKey(event),+ );+ });++ it("keys the same instant identically however the feed formats it", async () => {+ const { calendarBindingKey } = await import("./calendar");+ // The detector and this client receive the same event in different+ // shapes; a format difference must not mint a second identity.+ expect(+ calendarBindingKey({+ title: "Weekly review",+ start: "2026-08-13T18:30:00Z",+ end: "2026-08-13T19:00:00Z",+ }),+ ).toBe(+ calendarBindingKey({+ title: "Weekly review",+ start: "2026-08-13T18:30:00.000+00:00",+ end: "2026-08-13T19:00:00.000+00:00",+ }),+ );+ });++ it("gives two genuinely different events different keys", async () => {+ const { calendarBindingKey } = await import("./calendar");+ const a = {+ title: "Sync",+ start: "2026-08-13T18:30:00Z",+ end: "2026-08-13T19:00:00Z",+ };+ const b = { ...a, start: "2026-08-13T19:30:00Z" };+ expect(calendarBindingKey(a)).not.toBe(calendarBindingKey(b));+ });+});diff --git a/apps/screenpipe-app-tauri/lib/utils/calendar.ts b/apps/screenpipe-app-tauri/lib/utils/calendar.tsindex 4017af5e6..610909ffd 100644--- a/apps/screenpipe-app-tauri/lib/utils/calendar.ts+++ b/apps/screenpipe-app-tauri/lib/utils/calendar.ts@@ -540,6 +540,24 @@ export function findOverlappingEvent(return null;}+/**+ * Identity used to keep one calendar event bound to one meeting. Mirrors+ * `CalendarBinding::from_event` in the Rust detector so both writers claim the+ * same key: the provider id when there is one, otherwise the event's natural+ * identity (an event is the same event when title and exact window match).+ */+export function calendarBindingKey(event: CalendarEvent): string {+ if (event.id && event.id.length > 0) return event.id;+ // Normalize to epoch ms: the same instant reaches the detector and this+ // client in different shapes ("...:00Z" vs "...:00.000+00:00"), and the key+ // must be byte-identical or the same event gets claimed twice.+ const part = (raw: string) => {+ const ms = Date.parse(raw);+ return Number.isFinite(ms) ? String(ms) : raw;+ };+ return `${event.title}|${part(event.start)}|${part(event.end)}`;+}+export function attendeesToString(attendees?: string[] | null): string {if (!attendees) return "";return attendees.filter(Boolean).join(", ");diff --git a/crates/screenpipe-db/src/db/meetings.rs b/crates/screenpipe-db/src/db/meetings.rsindex dbec9d866..b89dc169d 100644--- a/crates/screenpipe-db/src/db/meetings.rs+++ b/crates/screenpipe-db/src/db/meetings.rs@@ -4,6 +4,18 @@use super::*;+/// True when the error is the `idx_meetings_calendar_event_id` uniqueness+/// violation — i.e. another meeting already owns this calendar event.+fn is_calendar_event_conflict(e: &SqlxError) -> bool {+ let msg = e.to_string();+ // SQLite names a partial unique index on a plain column by that column+ // ("meetings.calendar_event_id"); expression indexes report the index name+ // instead. Accept both so this stays correct if the index shape changes.+ msg.contains("UNIQUE constraint failed")+ && (msg.contains("meetings.calendar_event_id")+ || msg.contains("idx_meetings_calendar_event_id"))+}+impl DatabaseManager {// ── Meeting persistence ──────────────────────────────────────────//@@ -19,19 +31,66 @@ impl DatabaseManager {detection_source: &str,title: Option<&str>,attendees: Option<&str>,+ ) -> Result<i64, SqlxError> {+ self.insert_meeting_with_calendar(meeting_app, detection_source, title, attendees, None)+ .await+ }++ /// Insert a meeting, optionally claiming a calendar event as its identity.+ ///+ /// `calendar_event_id` is protected by `idx_meetings_calendar_event_id`, so+ /// a second meeting cannot claim an event another meeting already owns. On+ /// that collision the meeting is still created — it simply keeps no+ /// calendar identity and gets named from its own content instead.+ pub async fn insert_meeting_with_calendar(+ &self,+ meeting_app: &str,+ detection_source: &str,+ title: Option<&str>,+ attendees: Option<&str>,+ calendar_event_id: Option<&str>,+ ) -> Result<i64, SqlxError> {+ match self+ .try_insert_meeting(+ meeting_app,+ detection_source,+ title,+ attendees,+ calendar_event_id,+ )+ .await+ {+ Err(e) if calendar_event_id.is_some() && is_calendar_event_conflict(&e) => {+ // Lost the race to another meeting between the pre-check and+ // this insert. The event belongs to whoever claimed it first.+ self.try_insert_meeting(meeting_app, detection_source, None, None, None)+ .await+ }+ other => other,+ }+ }++ async fn try_insert_meeting(+ &self,+ meeting_app: &str,+ detection_source: &str,+ title: Option<&str>,+ attendees: Option<&str>,+ calendar_event_id: Option<&str>,) -> Result<i64, SqlxError> {let mut tx = self.begin_immediate_with_retry().await?;let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();let id = sqlx::query(- "INSERT INTO meetings (meeting_start, meeting_app, detection_source, title, attendees) VALUES (?1, ?2, ?3, ?4, ?5)",+ "INSERT INTO meetings (meeting_start, meeting_app, detection_source, title, attendees, calendar_event_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",).bind(&now).bind(meeting_app).bind(detection_source).bind(title).bind(attendees)+ .bind(calendar_event_id).execute(&mut **tx.conn()).await?.last_insert_rowid();@@ -39,6 +98,65 @@ impl DatabaseManager {Ok(id)}+ /// The meeting that already owns `calendar_event_id`, if any.+ pub async fn meeting_id_for_calendar_event(+ &self,+ calendar_event_id: &str,+ ) -> Result<Option<i64>, SqlxError> {+ if calendar_event_id.is_empty() {+ return Ok(None);+ }+ sqlx::query_scalar::<_, i64>("SELECT id FROM meetings WHERE calendar_event_id = ?1")+ .bind(calendar_event_id)+ .fetch_optional(&self.pool)+ .await+ }++ /// Claim `calendar_event_id` for `meeting_id`. Atomic, and idempotent for+ /// the owner: returns true when this meeting owns the event afterwards,+ /// whether this call did the claiming or a previous one did.+ ///+ /// Callers treat false as "another meeting owns this, drop the+ /// calendar-derived fields", so re-claiming your own event must not read+ /// as a refusal. Returns false only when the event belongs to someone+ /// else, this meeting already owns a *different* event, or the meeting+ /// does not exist.+ pub async fn bind_calendar_event(+ &self,+ meeting_id: i64,+ calendar_event_id: &str,+ ) -> Result<bool, SqlxError> {+ if calendar_event_id.is_empty() {+ return Ok(false);+ }+ let mut tx = self.begin_immediate_with_retry().await?;+ sqlx::query(+ "UPDATE meetings SET calendar_event_id = ?2 \+ WHERE id = ?1 \+ AND (calendar_event_id IS NULL OR calendar_event_id = '') \+ AND NOT EXISTS ( \+ SELECT 1 FROM meetings other \+ WHERE other.calendar_event_id = ?2 AND other.id != ?1 \+ )",+ )+ .bind(meeting_id)+ .bind(calendar_event_id)+ .execute(&mut **tx.conn())+ .await?;+ // Ownership, not "did this statement write a row" — the owner+ // re-claiming its own event updates nothing and still owns it.+ let owns = sqlx::query_scalar::<_, i64>(+ "SELECT COUNT(*) FROM meetings WHERE id = ?1 AND calendar_event_id = ?2",+ )+ .bind(meeting_id)+ .bind(calendar_event_id)+ .fetch_one(&mut **tx.conn())+ .await?+ > 0;+ tx.commit().await?;+ Ok(owns)+ }+/// End a meeting and persist the reason it ended. `end_reason` should be/// one of the `MEETING_END_REASON_*` constants (or `None` for legacy //// natural grace-timeout ends). The reason drives the auto-merge filterdiff --git a/crates/screenpipe-db/src/migrations/20260813000000_add_calendar_event_id_to_meetings.sql b/crates/screenpipe-db/src/migrations/20260813000000_add_calendar_event_id_to_meetings.sqlnew file mode 100644index 000000000..db0450ac1--- /dev/null+++ b/crates/screenpipe-db/src/migrations/20260813000000_add_calendar_event_id_to_meetings.sql@@ -0,0 +1,12 @@+-- A calendar event describes exactly one meeting.+--+-- Without an identity column the detector re-matched a still-running event to+-- every meeting that started inside its window, stamping the same title and+-- the same attendee list onto unrelated calls. The partial unique index makes+-- that impossible at the storage layer, so every write path — detector,+-- reopen-enrichment, and the client PUT — converges on the same invariant.+ALTER TABLE meetings ADD COLUMN calendar_event_id TEXT;++CREATE UNIQUE INDEX IF NOT EXISTS idx_meetings_calendar_event_id+ ON meetings (calendar_event_id)+ WHERE calendar_event_id IS NOT NULL AND calendar_event_id != '';diff --git a/crates/screenpipe-engine/src/meeting_watcher/audio_process/events.rs b/crates/screenpipe-engine/src/meeting_watcher/audio_process/events.rsindex 2f8455442..7a53349a7 100644--- a/crates/screenpipe-engine/src/meeting_watcher/audio_process/events.rs+++ b/crates/screenpipe-engine/src/meeting_watcher/audio_process/events.rs@@ -5,56 +5,13 @@use super::*;-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub(crate) struct CalendarEventSignal {- pub title: String,- pub start: String,- pub end: String,- #[serde(default)]- pub attendees: Vec<String>,- #[serde(default)]- pub is_all_day: bool,-}--#[derive(Debug, Clone, Deserialize)]-pub(crate) struct MeetingAutoEndRequest {- pub(crate) meeting_id: i64,- #[serde(default)]- pub(crate) reason: Option<String>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub(crate) struct DetectorStopSignal {- pub meeting_id: i64,- pub app: String,-}--pub(crate) fn find_overlapping_calendar_event(- events: &[CalendarEventSignal],-) -> (Option<String>, Option<Vec<String>>) {- let now = Utc::now();- for cal_event in events {- if let (Ok(start), Ok(end)) = (- DateTime::parse_from_rfc3339(&cal_event.start),- DateTime::parse_from_rfc3339(&cal_event.end),- ) {- let start_utc = start.with_timezone(&Utc);- let end_utc = end.with_timezone(&Utc);- if start_utc <= now && end_utc >= now {- return (- Some(cal_event.title.clone()),- if cal_event.attendees.is_empty() {- None- } else {- Some(cal_event.attendees.clone())- },- );- }- }- }- (None, None)-}+// These signals and the calendar matcher are shared with the ui_scan watcher.+// They used to be duplicated here, and the two copies drifting is how a single+// calendar event ended up owning two meetings — keep exactly one definition.+pub(crate) use crate::meeting_watcher::shared::calendar::{+ resolve_calendar_binding, CalendarBinding, CalendarEventSignal, DetectorStopSignal,+ MeetingAutoEndRequest,+};/// Apply an explicit `detector_stop_tracking` signal: when it targets the live/// meeting, suppress that session and move the detector to idle.diff --git a/crates/screenpipe-engine/src/meeting_watcher/audio_process/lifecycle.rs b/crates/screenpipe-engine/src/meeting_watcher/audio_process/lifecycle.rsindex 90aaff133..9bb1df6fc 100644--- a/crates/screenpipe-engine/src/meeting_watcher/audio_process/lifecycle.rs+++ b/crates/screenpipe-engine/src/meeting_watcher/audio_process/lifecycle.rs@@ -17,10 +17,11 @@ pub(crate) async fn start_or_adopt_auto_meeting(db: &DatabaseManager,manual_meeting: &tokio::sync::RwLock<Option<i64>>,platform: &str,- title: Option<&str>,- attendees: Option<&str>,+ calendar: Option<&CalendarBinding>,last_explicit_stop_id: Option<i64>,) -> AutoStartOutcome {+ let title = calendar.map(|c| c.title.as_str());+ let attendees = calendar.and_then(|c| c.attendees.as_deref());if let Some(id) = *manual_meeting.read().await {debug!("audio-process meeting detector: not starting {}, manual meeting {} is active",@@ -55,15 +56,32 @@ pub(crate) async fn start_or_adopt_auto_meeting(match merge_candidate {Ok(Some(recent)) => match db.reopen_meeting(recent.id).await {Ok(()) => {- if title.is_some() && recent.title.as_ref().is_none_or(|t| t.is_empty()) {- if let Err(e) = db- .update_meeting(recent.id, None, None, title, attendees, None, None)- .await- {- warn!(- "audio-process meeting detector: failed to enrich reopened meeting {}: {}",+ if let Some(calendar) = calendar {+ // Claim the event first: enrich only if this meeting owns it.+ match db.bind_calendar_event(recent.id, &calendar.key).await {+ Ok(true) => {+ if recent.title.as_ref().is_none_or(|t| t.is_empty()) {+ if let Err(e) = db+ .update_meeting(+ recent.id, None, None, title, attendees, None, None,+ )+ .await+ {+ warn!(+ "audio-process meeting detector: failed to enrich reopened meeting {}: {}",+ recent.id, e+ );+ }+ }+ }+ Ok(false) => debug!(+ "audio-process meeting detector: calendar event already bound, leaving meeting {} unenriched",+ recent.id+ ),+ Err(e) => warn!(+ "audio-process meeting detector: failed to bind calendar event to meeting {}: {}",recent.id, e- );+ ),}}if let Ok(meeting) = db.get_meeting_by_id(recent.id).await {@@ -76,16 +94,16 @@ pub(crate) async fn start_or_adopt_auto_meeting("audio-process meeting detector: failed to reopen meeting {}: {}",recent.id, e);- insert_new_audio_process_meeting(db, platform, title, attendees).await+ insert_new_audio_process_meeting(db, platform, calendar).await}},- Ok(None) => insert_new_audio_process_meeting(db, platform, title, attendees).await,+ Ok(None) => insert_new_audio_process_meeting(db, platform, calendar).await,Err(e) => {warn!("audio-process meeting detector: failed to find recent meeting: {}",e);- insert_new_audio_process_meeting(db, platform, title, attendees).await+ insert_new_audio_process_meeting(db, platform, calendar).await}}}@@ -93,11 +111,18 @@ pub(crate) async fn start_or_adopt_auto_meeting(pub(crate) async fn insert_new_audio_process_meeting(db: &DatabaseManager,platform: &str,- title: Option<&str>,- attendees: Option<&str>,+ calendar: Option<&CalendarBinding>,) -> AutoStartOutcome {+ let title = calendar.map(|c| c.title.as_str());+ let attendees = calendar.and_then(|c| c.attendees.as_deref());match db- .insert_meeting(platform, "audio_process", title, attendees)+ .insert_meeting_with_calendar(+ platform,+ "audio_process",+ title,+ attendees,+ calendar.map(|c| c.key.as_str()),+ ).await{Ok(id) => {@@ -234,14 +259,12 @@ pub(crate) async fn apply_state_action(pid,bundle_id,} => {- let (cal_title, cal_attendees) = find_overlapping_calendar_event(calendar_events);- let attendees_str = cal_attendees.as_ref().map(|a| a.join(", "));+ let calendar = resolve_calendar_binding(db, calendar_events, Utc::now()).await;let outcome = start_or_adopt_auto_meeting(db,manual_meeting,&platform,- cal_title.as_deref(),- attendees_str.as_deref(),+ calendar.as_ref(),last_explicit_stop_id,).await;diff --git a/crates/screenpipe-engine/src/meeting_watcher/audio_process/mod.rs b/crates/screenpipe-engine/src/meeting_watcher/audio_process/mod.rsindex 3e52ba2d9..ce94298e4 100644--- a/crates/screenpipe-engine/src/meeting_watcher/audio_process/mod.rs+++ b/crates/screenpipe-engine/src/meeting_watcher/audio_process/mod.rs@@ -17,13 +17,12 @@ use crate::meeting_watcher::shared::telemetry::{capture_detection_decision, capture_detection_outcome,};use crate::routes::meetings::{emit_meeting_status_changed, resolve_meeting_status_from};-use chrono::{DateTime, Utc};+use chrono::Utc;use futures::{FutureExt, StreamExt};use screenpipe_audio::meeting_detector::MeetingDetector;use screenpipe_audio::meeting_processes::{self, AudioInputProcess};use screenpipe_db::{DatabaseManager, MEETING_END_REASON_AUTO_END, MEETING_END_REASON_SHUTDOWN};use screenpipe_events::subscribe_to_event;-use serde::{Deserialize, Serialize};use std::collections::HashSet;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;diff --git a/crates/screenpipe-engine/src/meeting_watcher/audio_process/tests.rs b/crates/screenpipe-engine/src/meeting_watcher/audio_process/tests.rsindex 98120bc63..bf8241a59 100644--- a/crates/screenpipe-engine/src/meeting_watcher/audio_process/tests.rs+++ b/crates/screenpipe-engine/src/meeting_watcher/audio_process/tests.rs@@ -5,6 +5,7 @@//! candidate resolution, suppression, and lifecycle, sharing common fixtures.use super::*;+use crate::meeting_watcher::shared::calendar::find_overlapping_calendar_event;use screenpipe_db::DatabaseManager;fn chrome_process() -> AudioInputProcess {@@ -1122,7 +1123,7 @@ async fn active_meeting_blocks_audio_process_insert() {.unwrap();let manual_meeting = tokio::sync::RwLock::new(None);let outcome =- start_or_adopt_auto_meeting(&db, &manual_meeting, "Google Meet", None, None, None).await;+ start_or_adopt_auto_meeting(&db, &manual_meeting, "Google Meet", None, None).await;assert_eq!(outcome, AutoStartOutcome::BlockedByActive(active_id));let open_count: (i64,) =@@ -2084,3 +2085,403 @@ fn resolved_platform_identity_heals_pid_from_matching_candidate() {"an unresolved browser alone must not be adopted (could be any WebRTC page)");}++// ── Calendar event binding ───────────────────────────────────────────────+//+// A calendar event describes ONE meeting. These tests pin that invariant at+// the level the incident happened: real DB, real migrations, real lifecycle.++fn calendar_event(+ id: &str,+ title: &str,+ starts_in: chrono::Duration,+ lasts: chrono::Duration,+ attendees: &[&str],+) -> CalendarEventSignal {+ let start = Utc::now() + starts_in;+ CalendarEventSignal {+ id: id.to_string(),+ title: title.to_string(),+ start: start.to_rfc3339(),+ end: (start + lasts).to_rfc3339(),+ attendees: attendees.iter().map(|a| a.to_string()).collect(),+ is_all_day: false,+ }+}++/// Start a meeting exactly the way `apply_audio_process_action` does.+async fn start_meeting_with_calendar(+ db: &DatabaseManager,+ events: &[CalendarEventSignal],+ platform: &str,+) -> AutoStartOutcome {+ let manual_meeting = tokio::sync::RwLock::new(None);+ let calendar = resolve_calendar_binding(db, events, Utc::now()).await;+ start_or_adopt_auto_meeting(db, &manual_meeting, platform, calendar.as_ref(), None).await+}++async fn end_meeting_ago(db: &DatabaseManager, id: i64, ago: chrono::Duration) {+ let ended_at = (Utc::now() - ago)+ .format("%Y-%m-%dT%H:%M:%S%.3fZ")+ .to_string();+ db.end_meeting(id, &ended_at, None).await.unwrap();+}++/// Reproduces the 2026-08-13 incident. An 11:30–12:00 calendar event was still+/// running when a second, unrelated Google Meet started at 11:40 — 2m13s after+/// the first call ended, so past the 120s auto-merge window. Both rows were+/// stamped with the same calendar title and the same attendee list, so the+/// meetings list showed two identical entries and the second call carried+/// three people who were never in it.+#[tokio::test]+async fn calendar_event_binds_to_a_single_meeting() {+ let (_dir, db) = setup_db().await;+ let events = vec![calendar_event(+ "cal-evt-vercel",+ "chat between louis030195 and Ben Fleschman",+ chrono::Duration::minutes(-10),+ chrono::Duration::minutes(30),+ &[+ "[email protected]",+ "[email protected]",+ "[email protected]",+ ],+ )];++ let first = match start_meeting_with_calendar(&db, &events, "Google Meet").await {+ AutoStartOutcome::Started(id) => id,+ other => panic!("expected the first meeting to start, got {other:?}"),+ };+ let first_row = db.get_meeting_by_id(first).await.unwrap();+ assert_eq!(+ first_row.title.as_deref(),+ Some("chat between louis030195 and Ben Fleschman"),+ "the meeting inside the event window owns the calendar identity"+ );++ // Ended long enough ago that `find_recent_meeting_for_app(_, 120)` will not+ // adopt it — the second Meet becomes its own row, as it did in production.+ end_meeting_ago(&db, first, chrono::Duration::minutes(5)).await;++ let second = match start_meeting_with_calendar(&db, &events, "Google Meet").await {+ AutoStartOutcome::Started(id) => id,+ other => panic!("expected a second, separate meeting, got {other:?}"),+ };+ assert_ne!(first, second, "the second Meet must be its own row");++ let second_row = db.get_meeting_by_id(second).await.unwrap();+ assert!(+ second_row.title.as_deref().unwrap_or("").is_empty(),+ "a calendar event already bound to meeting {first} must not title \+ meeting {second} too — got {:?}",+ second_row.title+ );+ assert!(+ second_row.attendees.as_deref().unwrap_or("").is_empty(),+ "attendees from an already-bound event must not leak onto an \+ unrelated meeting — got {:?}",+ second_row.attendees+ );+}++/// The other half of the same incident: the call that genuinely *was* the+/// scheduled event started 26 seconds before it, so the strict+/// `start <= now` predicate missed and the row landed with no attendees at+/// all. Joining a moment early is the normal case, not an edge case.+#[tokio::test]+async fn meeting_joined_shortly_before_start_still_binds_the_event() {+ let (_dir, db) = setup_db().await;+ let events = vec![calendar_event(+ "cal-evt-early",+ "chat between louis030195 and Ben Fleschman",+ chrono::Duration::seconds(26),+ chrono::Duration::minutes(30),+ &["[email protected]", "[email protected]"],+ )];++ let id = match start_meeting_with_calendar(&db, &events, "Google Meet").await {+ AutoStartOutcome::Started(id) => id,+ other => panic!("expected the meeting to start, got {other:?}"),+ };+ let row = db.get_meeting_by_id(id).await.unwrap();+ assert_eq!(+ row.title.as_deref(),+ Some("chat between louis030195 and Ben Fleschman"),+ "a meeting joined 26s early belongs to the event about to start"+ );+ assert_eq!(+ row.attendees.as_deref(),+ Some("[email protected], [email protected]"),+ "attendees must come along with the title"+ );+}++/// A quick rejoin still lands inside the 120s merge window, so it adopts the+/// same row and keeps the calendar identity it already owns. Binding must not+/// break the normal drop-and-rejoin case.+#[tokio::test]+async fn quick_rejoin_keeps_its_own_calendar_identity() {+ let (_dir, db) = setup_db().await;+ let events = vec![calendar_event(+ "cal-evt-standup",+ "Standup",+ chrono::Duration::minutes(-5),+ chrono::Duration::minutes(30),+ &["[email protected]", "[email protected]"],+ )];++ let first = match start_meeting_with_calendar(&db, &events, "Google Meet").await {+ AutoStartOutcome::Started(id) => id,+ other => panic!("expected a meeting to start, got {other:?}"),+ };+ end_meeting_ago(&db, first, chrono::Duration::seconds(10)).await;++ let rejoined = start_meeting_with_calendar(&db, &events, "Google Meet").await;+ assert_eq!(+ rejoined,+ AutoStartOutcome::AdoptedActive(first),+ "a rejoin within the merge window continues the same meeting"+ );+ let row = db.get_meeting_by_id(first).await.unwrap();+ assert_eq!(row.title.as_deref(), Some("Standup"));+ assert_eq!(+ row.attendees.as_deref(),+ Some("[email protected], [email protected]")+ );+}++/// The DB is the backstop when two detectors race past the ownership check.+#[tokio::test]+async fn calendar_event_cannot_be_claimed_twice() {+ let (_dir, db) = setup_db().await;++ let first = db+ .insert_meeting_with_calendar(+ "Google Meet",+ "audio_process",+ Some("Sync"),+ None,+ Some("evt-1"),+ )+ .await+ .unwrap();+ assert_eq!(+ db.meeting_id_for_calendar_event("evt-1").await.unwrap(),+ Some(first)+ );++ end_meeting_ago(&db, first, chrono::Duration::minutes(5)).await;++ // Racing insert for the same event: the meeting is still created, just+ // without the identity that already belongs to `first`.+ let second = db+ .insert_meeting_with_calendar(+ "Google Meet",+ "audio_process",+ Some("Sync"),+ None,+ Some("evt-1"),+ )+ .await+ .unwrap();+ assert_ne!(first, second);+ let row = db.get_meeting_by_id(second).await.unwrap();+ assert_eq!(+ row.title, None,+ "a meeting that lost the race must not keep the calendar title"+ );+ assert_eq!(+ db.meeting_id_for_calendar_event("evt-1").await.unwrap(),+ Some(first),+ "the first claimant keeps the event"+ );++ // And the explicit bind path refuses too.+ assert!(!db.bind_calendar_event(second, "evt-1").await.unwrap());+ assert!(db.bind_calendar_event(second, "evt-2").await.unwrap());+ assert!(+ !db.bind_calendar_event(second, "evt-3").await.unwrap(),+ "a meeting that already owns an event does not switch to another"+ );+}++/// Matching must not depend on the order the publisher emitted events in.+#[test]+fn calendar_match_prefers_the_event_in_progress() {+ let now = Utc::now();+ let upcoming = calendar_event(+ "upcoming",+ "Next call",+ chrono::Duration::seconds(60),+ chrono::Duration::minutes(30),+ &[],+ );+ let in_progress = calendar_event(+ "in-progress",+ "Current call",+ chrono::Duration::minutes(-5),+ chrono::Duration::minutes(30),+ &[],+ );++ for events in [+ vec![upcoming.clone(), in_progress.clone()],+ vec![in_progress.clone(), upcoming.clone()],+ ] {+ let m = find_overlapping_calendar_event(&events, now).expect("expected a match");+ assert_eq!(+ m.key, "in-progress",+ "an event already running wins over one about to start, in any order"+ );+ }+}++#[test]+fn calendar_match_ignores_events_outside_the_join_window() {+ let now = Utc::now();+ let too_early = vec![calendar_event(+ "later",+ "Much later",+ chrono::Duration::minutes(30),+ chrono::Duration::minutes(30),+ &[],+ )];+ assert!(+ find_overlapping_calendar_event(&too_early, now).is_none(),+ "an event 30 minutes out must not name the meeting happening now"+ );++ let all_day = vec![CalendarEventSignal {+ is_all_day: true,+ ..calendar_event(+ "all-day",+ "Offsite",+ chrono::Duration::hours(-2),+ chrono::Duration::hours(8),+ &[],+ )+ }];+ assert!(+ find_overlapping_calendar_event(&all_day, now).is_none(),+ "all-day events describe a day, not a meeting"+ );+}++/// Events from feeds that omit a provider id still get a stable identity, so+/// the one-event-one-meeting rule holds for them too.+#[test]+fn events_without_a_provider_id_still_get_a_stable_key() {+ let now = Utc::now();+ let mut event = calendar_event(+ "",+ "Weekly review",+ chrono::Duration::minutes(-1),+ chrono::Duration::minutes(30),+ &[],+ );+ event.id = String::new();+ let first = find_overlapping_calendar_event(std::slice::from_ref(&event), now).unwrap();+ let second = find_overlapping_calendar_event(&[event], now).unwrap();+ assert_eq!(first.key, second.key, "the same event yields the same key");+ assert!(first.key.contains("Weekly review"));+}++/// Re-claiming an event you already own has to succeed. Callers read `false`+/// as "someone else owns this, drop the calendar fields", so a non-idempotent+/// bind silently discards a legitimate re-enrichment — and a meeting whose+/// title write failed the first time could never be filled in again.+#[tokio::test]+async fn rebinding_the_same_event_to_its_owner_succeeds() {+ let (_dir, db) = setup_db().await;+ let id = db+ .insert_meeting("Google Meet", "audio_process", None, None)+ .await+ .unwrap();++ assert!(db.bind_calendar_event(id, "evt-1").await.unwrap());+ assert!(+ db.bind_calendar_event(id, "evt-1").await.unwrap(),+ "the owner re-claiming its own event is a no-op that still means 'yes, it is yours'"+ );+ assert!(+ !db.bind_calendar_event(id, "evt-other").await.unwrap(),+ "but it still must not switch to a different event"+ );+}++/// The manual "start from a Coming Up event" path writes the same calendar+/// title and attendees, so it has to claim the event too. Otherwise the event+/// stays unowned and the detector will happily stamp it onto the next meeting.+#[tokio::test]+async fn manually_started_meeting_claims_its_calendar_event() {+ let (_dir, db) = setup_db().await;+ let events = vec![calendar_event(+ "cal-evt-manual",+ "Design review",+ chrono::Duration::minutes(-5),+ chrono::Duration::minutes(30),+ &["[email protected]", "[email protected]"],+ )];++ // What the manual path does: create the row, then stamp the event onto it.+ let manual = db+ .insert_meeting("manual", "manual", None, None)+ .await+ .unwrap();+ let binding = find_overlapping_calendar_event(&events, Utc::now()).unwrap();+ assert!(db.bind_calendar_event(manual, &binding.key).await.unwrap());+ db.update_meeting(+ manual,+ None,+ None,+ Some(&binding.title),+ binding.attendees.as_deref(),+ None,+ None,+ )+ .await+ .unwrap();+ end_meeting_ago(&db, manual, chrono::Duration::minutes(5)).await;++ // A later, unrelated call inside the same window must not inherit it.+ let auto = match start_meeting_with_calendar(&db, &events, "Google Meet").await {+ AutoStartOutcome::Started(id) => id,+ other => panic!("expected a separate meeting, got {other:?}"),+ };+ let row = db.get_meeting_by_id(auto).await.unwrap();+ assert!(+ row.title.as_deref().unwrap_or("").is_empty(),+ "a manually claimed event must not also name the next meeting — got {:?}",+ row.title+ );+}++/// The detector and the client each build this key from their own copy of the+/// event. Publishers spell the same instant differently, so the key has to+/// normalize or one event would be claimed twice under two identities.+#[test]+fn binding_key_is_stable_across_timestamp_formats() {+ let now = Utc::now();+ let base = Utc::now() - chrono::Duration::minutes(5);+ let end = base + chrono::Duration::minutes(30);+ let mk = |start: String, end: String| CalendarEventSignal {+ id: String::new(),+ title: "Weekly review".to_string(),+ start,+ end,+ attendees: vec![],+ is_all_day: false,+ };++ let rfc = mk(base.to_rfc3339(), end.to_rfc3339());+ let zulu = mk(+ base.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string(),+ end.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string(),+ );+ let a = find_overlapping_calendar_event(&[rfc], now).unwrap();+ let b = find_overlapping_calendar_event(&[zulu], now).unwrap();+ assert_eq!(+ a.key, b.key,+ "the same instant in two RFC3339 spellings is one event"+ );+}diff --git a/crates/screenpipe-engine/src/meeting_watcher/shared/calendar.rs b/crates/screenpipe-engine/src/meeting_watcher/shared/calendar.rsindex 09c41a31a..fdbd0d53e 100644--- a/crates/screenpipe-engine/src/meeting_watcher/shared/calendar.rs+++ b/crates/screenpipe-engine/src/meeting_watcher/shared/calendar.rs@@ -13,6 +13,10 @@ use tracing::{error, info, warn};#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub(crate) struct CalendarEventSignal {+ /// Stable provider event id (`CalendarEventItem::id`). Empty for feeds that+ /// don't supply one — such events are never bound, only matched.+ #[serde(default)]+ pub id: String,pub title: String,pub start: String,pub end: String,@@ -35,32 +39,128 @@ pub(crate) struct DetectorStopSignal {pub app: String,}-/// Check if any non-all-day calendar event overlaps with the current time.-/// Returns (title, attendees) of the first matching event, or (None, None).+/// How early a meeting may start and still belong to a scheduled event.+/// People join a minute or two before the hour; without this the row lands+/// with no title and no attendees even though the event is right there.+const CALENDAR_JOIN_LEAD: chrono::TimeDelta = chrono::TimeDelta::minutes(3);++/// Epoch milliseconds for an RFC3339 timestamp, falling back to the raw string+/// when it will not parse. Used only for the binding key: two publishers can+/// describe the same instant as `...:00Z` and `...:00.000+00:00`, and the key+/// has to be identical either way or the same event would be claimed twice.+fn timestamp_key_part(raw: &str) -> String {+ DateTime::parse_from_rfc3339(raw)+ .map(|t| t.timestamp_millis().to_string())+ .unwrap_or_else(|_| raw.to_string())+}++/// A calendar event resolved for a meeting, with the identity used to keep it+/// bound to exactly one meeting.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct CalendarBinding {+ /// Dedupe identity, persisted in `meetings.calendar_event_id`.+ pub key: String,+ pub title: String,+ /// Pre-joined for storage; `None` when the event lists nobody.+ pub attendees: Option<String>,+}++impl CalendarBinding {+ fn from_event(event: &CalendarEventSignal) -> Self {+ // Prefer the provider id. Some feeds omit it, so fall back to the+ // event's natural identity — an event is the same event when its+ // title and exact window match.+ let key = if event.id.is_empty() {+ format!(+ "{}|{}|{}",+ event.title,+ timestamp_key_part(&event.start),+ timestamp_key_part(&event.end)+ )+ } else {+ event.id.clone()+ };+ Self {+ key,+ title: event.title.clone(),+ attendees: if event.attendees.is_empty() {+ None+ } else {+ Some(event.attendees.join(", "))+ },+ }+ }+}++/// Best non-all-day calendar event for a meeting starting at `now`.+///+/// An event that is already in progress wins over one about to start; ties+/// break toward the event whose start is nearest `now`. Deterministic — it+/// never depends on the order the publisher happened to emit events in.pub(crate) fn find_overlapping_calendar_event(events: &[CalendarEventSignal],-) -> (Option<String>, Option<Vec<String>>) {- let now = Utc::now();- for cal_event in events {- if let (Ok(start), Ok(end)) = (- DateTime::parse_from_rfc3339(&cal_event.start),- DateTime::parse_from_rfc3339(&cal_event.end),- ) {- let start_utc = start.with_timezone(&Utc);- let end_utc = end.with_timezone(&Utc);- if start_utc <= now && end_utc >= now {- return (- Some(cal_event.title.clone()),- if cal_event.attendees.is_empty() {- None- } else {- Some(cal_event.attendees.clone())- },- );- }+ now: DateTime<Utc>,+) -> Option<CalendarBinding> {+ let mut best: Option<((u8, i64), &CalendarEventSignal)> = None;++ for event in events {+ if event.is_all_day {+ continue;+ }+ let (Ok(start), Ok(end)) = (+ DateTime::parse_from_rfc3339(&event.start),+ DateTime::parse_from_rfc3339(&event.end),+ ) else {+ continue;+ };+ let start = start.with_timezone(&Utc);+ let end = end.with_timezone(&Utc);++ let rank = if start <= now && end >= now {+ 0 // in progress+ } else if start > now && start <= now + CALENDAR_JOIN_LEAD {+ 1 // about to start, we joined early+ } else {+ continue;+ };++ let score = (rank, (start - now).num_seconds().abs());+ if best.as_ref().is_none_or(|(current, _)| score < *current) {+ best = Some((score, event));+ }+ }++ best.map(|(_, event)| CalendarBinding::from_event(event))+}++/// Resolve the calendar event that should name a meeting about to start.+///+/// Returns `None` when the best match already belongs to another meeting. One+/// calendar event describes one meeting: a 30-minute event that is still+/// running when an unrelated second call begins must not stamp its title and+/// attendee list onto that call too.+pub(crate) async fn resolve_calendar_binding(+ db: &DatabaseManager,+ events: &[CalendarEventSignal],+ now: DateTime<Utc>,+) -> Option<CalendarBinding> {+ let binding = find_overlapping_calendar_event(events, now)?;+ match db.meeting_id_for_calendar_event(&binding.key).await {+ Ok(None) => Some(binding),+ Ok(Some(owner)) => {+ info!(+ "calendar event {:?} already belongs to meeting {} — leaving this meeting to be named from its own content",+ binding.title, owner+ );+ None+ }+ Err(e) => {+ // Fail closed: a wrong title with wrong attendees is worse than+ // no title, which the summarizer fills in from content anyway.+ warn!("failed to check calendar event ownership: {e}");+ None}}- (None, None)}/// True if a non-all-day calendar event is happening at `now`. Used as a@@ -93,10 +193,20 @@ pub(crate) fn has_active_calendar_event(pub(crate) async fn insert_new_meeting(db: &DatabaseManager,app: &str,- title: Option<&str>,- attendees: Option<&str>,+ calendar: Option<&CalendarBinding>,) -> i64 {- match db.insert_meeting(app, "ui_scan", title, attendees).await {+ let title = calendar.map(|c| c.title.as_str());+ let attendees = calendar.and_then(|c| c.attendees.as_deref());+ match db+ .insert_meeting_with_calendar(+ app,+ "ui_scan",+ title,+ attendees,+ calendar.map(|c| c.key.as_str()),+ )+ .await+ {Ok(id) => {info!("meeting v2: meeting started (id={}, app={}, title={:?})",diff --git a/crates/screenpipe-engine/src/meeting_watcher/ui_scan/lifecycle.rs b/crates/screenpipe-engine/src/meeting_watcher/ui_scan/lifecycle.rsindex ee44ae333..29076efbb 100644--- a/crates/screenpipe-engine/src/meeting_watcher/ui_scan/lifecycle.rs+++ b/crates/screenpipe-engine/src/meeting_watcher/ui_scan/lifecycle.rs@@ -309,9 +309,9 @@ pub(crate) async fn apply_state_action(StateAction::StartMeeting { app } => {// Fresh meeting -> reset the flap counter for outcome telemetry.*flap_count = 0;- // Calendar enrichment: find overlapping calendar event- let (cal_title, cal_attendees) = find_overlapping_calendar_event(calendar_events);- let attendees_str = cal_attendees.as_ref().map(|a| a.join(", "));+ // Calendar enrichment, skipped when the event already names another+ // meeting — one calendar event describes one meeting.+ let calendar = resolve_calendar_binding(db, calendar_events, Utc::now()).await;// Try to merge with recently-ended meeting. The DB query// already filters out explicit_stop rows; the@@ -336,25 +336,34 @@ pub(crate) async fn apply_state_action("meeting v2: reopened recent meeting (id={}, app={})",recent.id, app);- // Enrich reopened meeting with calendar data if it has none- if cal_title.is_some() && recent.title.as_ref().is_none_or(|t| t.is_empty())- {- if let Err(e) = db- .update_meeting(- recent.id,- None,- None,- cal_title.as_deref(),- attendees_str.as_deref(),- None,- None,- )- .await- {- warn!(- "meeting v2: failed to enrich reopened meeting {}: {}",+ // Enrich reopened meeting with calendar data if it has+ // none — but only once this meeting owns the event.+ if let Some(calendar) = calendar.as_ref() {+ match db.bind_calendar_event(recent.id, &calendar.key).await {+ Ok(true) if recent.title.as_ref().is_none_or(|t| t.is_empty()) => {+ if let Err(e) = db+ .update_meeting(+ recent.id,+ None,+ None,+ Some(calendar.title.as_str()),+ calendar.attendees.as_deref(),+ None,+ None,+ )+ .await+ {+ warn!(+ "meeting v2: failed to enrich reopened meeting {}: {}",+ recent.id, e+ );+ }+ }+ Ok(_) => {}+ Err(e) => warn!(+ "meeting v2: failed to bind calendar event to meeting {}: {}",recent.id, e- );+ ),}}(recent.id, "auto_reopen")@@ -362,32 +371,19 @@ pub(crate) async fn apply_state_action(Err(e) => {warn!("meeting v2: failed to reopen meeting {}: {}", recent.id, e);(- insert_new_meeting(- db,- &app,- cal_title.as_deref(),- attendees_str.as_deref(),- )- .await,+ insert_new_meeting(db, &app, calendar.as_ref()).await,"auto_start",)}},Ok(None) => (- insert_new_meeting(db, &app, cal_title.as_deref(), attendees_str.as_deref())- .await,+ insert_new_meeting(db, &app, calendar.as_ref()).await,"auto_start",),Err(e) => {warn!("meeting v2: failed to find recent meeting: {}", e);(- insert_new_meeting(- db,- &app,- cal_title.as_deref(),- attendees_str.as_deref(),- )- .await,+ insert_new_meeting(db, &app, calendar.as_ref()).await,"auto_start",)}diff --git a/crates/screenpipe-engine/src/meeting_watcher/ui_scan/tests.rs b/crates/screenpipe-engine/src/meeting_watcher/ui_scan/tests.rsindex 0e4b9bfa2..d20a4b3a8 100644--- a/crates/screenpipe-engine/src/meeting_watcher/ui_scan/tests.rs+++ b/crates/screenpipe-engine/src/meeting_watcher/ui_scan/tests.rs@@ -526,6 +526,7 @@ fn test_calendar_event_keep_alive() {let now = Utc::now();let rfc = |t: DateTime<Utc>| t.to_rfc3339();let ev = |start, end, all_day| CalendarEventSignal {+ id: "cal-standup".to_string(),title: "Standup".to_string(),start: rfc(start),end: rfc(end),diff --git a/crates/screenpipe-engine/src/routes/meetings.rs b/crates/screenpipe-engine/src/routes/meetings.rsindex 7d07d795e..cb5e8cfdb 100644--- a/crates/screenpipe-engine/src/routes/meetings.rs+++ b/crates/screenpipe-engine/src/routes/meetings.rs@@ -33,6 +33,11 @@ pub struct UpdateMeetingRequest {pub attendees: Option<String>,pub note: Option<String>,pub meeting_app: Option<String>,+ /// Set when `title`/`attendees` come from a calendar event. The event is+ /// claimed for this meeting first; if another meeting already owns it, the+ /// calendar-derived fields are dropped and the rest of the update applies.+ /// One calendar event describes one meeting.+ pub calendar_event_id: Option<String>,}#[derive(OaSchema, Deserialize, Debug)]@@ -64,6 +69,41 @@ pub struct StartMeetingRequest {pub app: Option<String>,pub title: Option<String>,pub attendees: Option<String>,+ /// Set when `title`/`attendees` come from a calendar event, e.g. starting+ /// from a "Coming Up" entry. Claimed for this meeting so the same event+ /// cannot also name the next one. See [`claim_calendar_event`].+ pub calendar_event_id: Option<String>,+}++/// Whether calendar-sourced `title`/`attendees` may be written to this meeting.+///+/// One calendar event describes one meeting, so a caller passing an event id is+/// claiming it: true means this meeting owns it (now or already), false means+/// another meeting does and the calendar-derived fields must be dropped.+/// Callers that aren't sourcing from a calendar pass `None` and are unaffected.+async fn claim_calendar_event(+ db: &DatabaseManager,+ meeting_id: i64,+ calendar_event_id: Option<&str>,+) -> bool {+ match calendar_event_id {+ Some(event_id) if !event_id.is_empty() => {+ match db.bind_calendar_event(meeting_id, event_id).await {+ Ok(owned) => owned,+ Err(e) => {+ // Fail closed: a wrong title with wrong attendees is worse+ // than none, which the summarizer fills in from content.+ tracing::warn!(+ "failed to claim calendar event for meeting {}: {}",+ meeting_id,+ e+ );+ false+ }+ }+ }+ _ => true,+ }}#[derive(OaSchema, Deserialize, Debug)]@@ -564,14 +604,21 @@ pub(crate) async fn update_meeting_handler(Path(id): Path<i64>,axum::Json(body): axum::Json<UpdateMeetingRequest>,) -> Result<JsonResponse<MeetingRecord>, (StatusCode, JsonResponse<Value>)> {+ let (title, attendees) =+ if claim_calendar_event(&state.db, id, body.calendar_event_id.as_deref()).await {+ (body.title.as_deref(), body.attendees.as_deref())+ } else {+ (None, None)+ };+state.db.update_meeting(id,body.meeting_start.as_deref(),body.meeting_end.as_deref(),- body.title.as_deref(),- body.attendees.as_deref(),+ title,+ attendees,body.note.as_deref(),body.meeting_app.as_deref(),)@@ -796,7 +843,9 @@ pub(crate) async fn start_meeting_handler(.as_deref().is_none_or(|s| s.trim().is_empty())});- if title_update.is_some() || attendees_update.is_some() {+ let may_enrich =+ claim_calendar_event(&state.db, active_id, body.calendar_event_id.as_deref()).await;+ if may_enrich && (title_update.is_some() || attendees_update.is_some()) {if let Err(e) = state.db.update_meeting(@@ -824,7 +873,9 @@ pub(crate) async fn start_meeting_handler(// body doesn't wipe out detector-stamped fields.let title_update = body.title.as_deref().filter(|t| !t.trim().is_empty());let attendees_update = body.attendees.as_deref().filter(|a| !a.trim().is_empty());- if title_update.is_some() || attendees_update.is_some() {+ let may_enrich =+ claim_calendar_event(&state.db, active_id, body.calendar_event_id.as_deref()).await;+ if may_enrich && (title_update.is_some() || attendees_update.is_some()) {if let Err(e) = state.db.update_meeting(@@ -855,11 +906,12 @@ pub(crate) async fn start_meeting_handler(} else {state.db- .insert_meeting(+ .insert_meeting_with_calendar(app,"manual",body.title.as_deref(),body.attendees.as_deref(),+ body.calendar_event_id.as_deref().filter(|e| !e.is_empty()),).await.map_err(|e| {@@ -1205,6 +1257,62 @@ mod tests {use super::*;use serde_json::json;+ async fn claim_test_db() -> (tempfile::TempDir, DatabaseManager) {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("claim-calendar-event.db");+ let db = DatabaseManager::new(&path.to_string_lossy(), Default::default())+ .await+ .unwrap();+ let writer = db.coordinated_writer().lock().await.unwrap();+ sqlx::migrate!("../screenpipe-db/src/migrations")+ .run(writer.pool())+ .await+ .unwrap();+ drop(writer);+ (dir, db)+ }++ /// Both write paths (`PUT /meetings/{id}` and `POST /meetings/start`) gate+ /// calendar-sourced fields on this one decision, so it carries the+ /// one-event-one-meeting rule for the whole HTTP surface.+ #[tokio::test]+ async fn claim_calendar_event_enforces_single_ownership() {+ let (_dir, db) = claim_test_db().await;+ let first = db+ .insert_meeting("Google Meet", "audio_process", None, None)+ .await+ .unwrap();++ // Callers not sourcing from a calendar are never gated.+ assert!(claim_calendar_event(&db, first, None).await);+ assert!(claim_calendar_event(&db, first, Some("")).await);++ // Claiming a free event succeeds and actually persists ownership.+ assert!(claim_calendar_event(&db, first, Some("evt-1")).await);+ assert_eq!(+ db.meeting_id_for_calendar_event("evt-1").await.unwrap(),+ Some(first)+ );++ // The owner re-claiming is idempotent, not a refusal.+ assert!(claim_calendar_event(&db, first, Some("evt-1")).await);++ // A second meeting cannot take it, so its calendar fields get dropped.+ db.end_meeting(first, "2026-08-13T18:38:10.000Z", None)+ .await+ .unwrap();+ let second = db+ .insert_meeting("Google Meet", "audio_process", None, None)+ .await+ .unwrap();+ assert!(!claim_calendar_event(&db, second, Some("evt-1")).await);+ assert_eq!(+ db.meeting_id_for_calendar_event("evt-1").await.unwrap(),+ Some(first),+ "a losing claim must not move the event"+ );+ }+#[test]fn export_request_defaults_to_audio_but_allows_video_only() {let default: ExportRequest =diff --git a/docs/coverage/CORE.md b/docs/coverage/CORE.mdindex 9ee30613d..ee17bc8c8 100644--- a/docs/coverage/CORE.md+++ b/docs/coverage/CORE.md@@ -9,10 +9,10 @@ confidence, and criticality.- Tracked crates: screenpipe-engine, screenpipe-db, screenpipe-sqlite-coordinator, screenpipe-audio, screenpipe-screen, screenpipe-a11y- Mapped suites: 32- Mapped Rust files: 321-- Active test blocks: 3071+- Active test blocks: 3082- Ignored/manual test blocks: 137-- Declared test blocks: 3208-- Weighted coverage points: 2528.1+- Declared test blocks: 3219+- Weighted coverage points: 2538.8Confidence weights: strong=1.0, partial=0.7, conditional=0.4, smoke=0.3.Criticality weights: high=1.0, medium=0.7, low=0.4.@@ -23,15 +23,15 @@ are explicitly enabled in a runtime lane.| Platform | Suites | Active tests | Ignored tests | Weighted points | Layers | Flows | Critical score || --- | --- | --- | --- | --- | --- | --- | --- |-| windows | 29 | 2940 | 132 | 2468.1 | 21 | 11 | 100% |-| macos | 29 | 2993 | 112 | 2478.5 | 22 | 11 | 100% |-| linux | 25 | 2626 | 105 | 2184.9 | 20 | 11 | 100% |+| windows | 29 | 2951 | 132 | 2478.8 | 21 | 11 | 100% |+| macos | 29 | 3004 | 112 | 2489.2 | 22 | 11 | 100% |+| linux | 25 | 2627 | 105 | 2185.6 | 20 | 11 | 100% |## Crate Summary| Crate | Suites | Integration files | Source unit files | Active tests | Ignored tests | Weighted points | Flows || --- | --- | --- | --- | --- | --- | --- | --- |-| screenpipe-engine | 10 | 18 | 102 | 1442 | 42 | 1105.3 | 10 |+| screenpipe-engine | 10 | 18 | 102 | 1453 | 42 | 1116.0 | 10 || screenpipe-db | 5 | 52 | 14 | 447 | 16 | 424.2 | 9 || screenpipe-sqlite-coordinator | 1 | 0 | 2 | 16 | 0 | 16.0 | 2 || screenpipe-audio | 6 | 25 | 51 | 591 | 43 | 517.4 | 5 |@@ -68,8 +68,8 @@ bun run coverage:core -- --llvm-cov-summary ../../docs/coverage/core-llvm-cov-su| database | 6 suites / 366 active / 12 ignored / 343.2 pts | 6 suites / 366 active / 12 ignored / 343.2 pts | 6 suites / 366 active / 12 ignored / 343.2 pts || db-search | 2 suites / 111 active / 9 ignored / 111.0 pts | 2 suites / 111 active / 9 ignored / 111.0 pts | 2 suites / 111 active / 9 ignored / 111.0 pts || engine-lifecycle | 6 suites / 208 active / 1 ignored / 183.6 pts | 6 suites / 208 active / 1 ignored / 183.6 pts | 5 suites / 202 active / 1 ignored / 181.9 pts |-| local-api | 2 suites / 325 active / 9 ignored / 229.3 pts | 2 suites / 325 active / 9 ignored / 229.3 pts | 2 suites / 325 active / 9 ignored / 229.3 pts |-| meeting | 6 suites / 1407 active / 19 ignored / 1150.2 pts | 6 suites / 1407 active / 19 ignored / 1150.2 pts | 4 suites / 1129 active / 15 ignored / 894.7 pts |+| local-api | 2 suites / 326 active / 9 ignored / 230.0 pts | 2 suites / 326 active / 9 ignored / 230.0 pts | 2 suites / 326 active / 9 ignored / 230.0 pts |+| meeting | 6 suites / 1418 active / 19 ignored / 1160.9 pts | 6 suites / 1418 active / 19 ignored / 1160.9 pts | 4 suites / 1130 active / 15 ignored / 895.4 pts || ocr | 4 suites / 124 active / 7 ignored / 118.3 pts | 4 suites / 128 active / 7 ignored / 123.8 pts | 3 suites / 119 active / 6 ignored / 114.8 pts || os-integration | 1 suites / 6 active / 0 ignored / 1.7 pts | 1 suites / 6 active / 0 ignored / 1.7 pts | - || performance | 13 suites / 1373 active / 67 ignored / 1211.2 pts | 14 suites / 1471 active / 70 ignored / 1250.4 pts | 13 suites / 1373 active / 67 ignored / 1211.2 pts |@@ -79,8 +79,8 @@ bun run coverage:core -- --llvm-cov-summary ../../docs/coverage/core-llvm-cov-su| speaker | 2 suites / 348 active / 8 ignored / 348.0 pts | 2 suites / 348 active / 8 ignored / 348.0 pts | 2 suites / 348 active / 8 ignored / 348.0 pts || storage | 3 suites / 473 active / 29 ignored / 383.6 pts | 3 suites / 473 active / 29 ignored / 383.6 pts | 3 suites / 473 active / 29 ignored / 383.6 pts || sync | 1 suites / 462 active / 3 ignored / 323.4 pts | 1 suites / 462 active / 3 ignored / 323.4 pts | 1 suites / 462 active / 3 ignored / 323.4 pts |-| timeline | 4 suites / 931 active / 33 ignored / 757.3 pts | 4 suites / 931 active / 33 ignored / 757.3 pts | 4 suites / 931 active / 33 ignored / 757.3 pts |-| transcription | 5 suites / 698 active / 40 ignored / 551.2 pts | 5 suites / 698 active / 40 ignored / 551.2 pts | 5 suites / 698 active / 40 ignored / 551.2 pts |+| timeline | 4 suites / 932 active / 33 ignored / 758.0 pts | 4 suites / 932 active / 33 ignored / 758.0 pts | 4 suites / 932 active / 33 ignored / 758.0 pts |+| transcription | 5 suites / 699 active / 40 ignored / 551.9 pts | 5 suites / 699 active / 40 ignored / 551.9 pts | 5 suites / 699 active / 40 ignored / 551.9 pts || ui-events | 4 suites / 701 active / 28 ignored / 533.9 pts | 3 suites / 652 active / 5 ignored / 499.6 pts | 3 suites / 652 active / 5 ignored / 499.6 pts || vision-capture | 5 suites / 492 active / 32 ignored / 389.9 pts | 5 suites / 496 active / 32 ignored / 395.4 pts | 4 suites / 487 active / 31 ignored / 386.4 pts |@@ -133,14 +133,14 @@ bun run coverage:core -- --llvm-cov-summary ../../docs/coverage/core-llvm-cov-su| db-runtime-reliability | screenpipe-db | windows, macos, linux | database, performance | performance-liveness | high | partial | mixed | 13 | 30 | 6 | SQLite hard-fault classification, failpoint VFS injection, fresh-identity recovery verification with integrity/FK/write canaries, query cancellation, close-severs-connections regressions, multi-pool WAL parity, runtime version pinning, and WAL chaos plus memory-pressure probes, plus read-only quarantine self-heal verification for transient IOERR faults. || db-search-indexing | screenpipe-db | windows, macos, linux | db-search, ocr, accessibility, performance | local-api-search, capture-ocr-pipeline, accessibility-ui-events, performance-liveness | high | strong | mixed | 13 | 105 | 4 | FTS, tokenizer, OCR snapshot search, query planning, ordering, accessibility search, and contention coverage. || db-timeline-frames | screenpipe-db | windows, macos, linux | database, timeline, storage, performance | timeline-streaming, performance-liveness | high | strong | mixed | 18 | 175 | 3 | Frame/audio joins, timeline query shape, suggestions frames, write queue, DB primitives (src/db.rs split into src/db/ modules), feedback record upserts, media eviction anti-join regressions, SAF output registry, semantic storage, and timeline performance. |-| engine-api-routes | screenpipe-engine | windows, macos, linux | local-api, timeline, meeting, transcription | local-api-search, timeline-streaming, meeting-live-notes, audio-record-transcribe | high | partial | mixed | 31 | 319 | 4 | Route/unit coverage for search, health, streaming, meetings, time/timezone, and transcription. Legacy endpoint/websocket tests require local data and remain ignored. |+| engine-api-routes | screenpipe-engine | windows, macos, linux | local-api, timeline, meeting, transcription | local-api-search, timeline-streaming, meeting-live-notes, audio-record-transcribe | high | partial | mixed | 31 | 320 | 4 | Route/unit coverage for search, health, streaming, meetings, time/timezone, and transcription. Legacy endpoint/websocket tests require local data and remain ignored. || engine-capture-timeline | screenpipe-engine | windows, macos, linux | vision-capture, timeline, storage, performance | capture-ocr-pipeline, timeline-streaming, performance-liveness | high | partial | mixed | 23 | 260 | 26 | Covers capture trigger logic, frame/audio linking, hot cache, timeline refresh regressions, fragmented MP4 extraction, and HD-mode control. Several real-data tests are intentionally ignored by default. || engine-config-lifecycle | screenpipe-engine | windows, macos, linux | configuration, engine-lifecycle, performance | settings-to-engine-config, engine-health-lifecycle, performance-liveness | high | strong | mixed | 11 | 111 | 1 | Fast logic coverage for the config bridge, tray health debounce, sleep/power policies, and queue backpressure. || engine-db-recovery-cli | screenpipe-engine | windows, macos, linux | database, engine-lifecycle | engine-health-lifecycle, performance-liveness | high | strong | unit | 1 | 8 | 0 | Exact DB/WAL/SHM working-copy preservation, rollback on archive failure, and restart repair for crashes during the multi-file generation swap. || engine-focus-os | screenpipe-engine | windows, macos | engine-lifecycle, os-integration | engine-health-lifecycle, performance-liveness | medium | conditional | unit | 3 | 6 | 0 | Platform focus-tracker parsing/helpers. These files are cfg-gated and only execute on their target OS. || engine-local-api-search-integration | screenpipe-engine | windows, macos, linux | local-api, db-search | local-api-search | high | strong | integration | 1 | 6 | 5 | Active /search route test builds an audio-disabled router, seeds captured-screen-shaped OCR data into an in-memory DB, and asserts the HTTP response and pagination. || engine-meeting-privacy-sync | screenpipe-engine | windows, macos, linux | meeting, privacy, ui-events, pipes, sync | meeting-live-notes, privacy-and-redaction, accessibility-ui-events, performance-liveness | medium | strong | unit | 30 | 462 | 3 | Unit-heavy coverage for privacy filter policy, capture exclusions, UI recorder safety, pipes/live-view/structured-output helpers, sync helpers, and CLI parsing. Meeting detection moved to the engine-meeting-watcher suite. |-| engine-meeting-watcher | screenpipe-engine | windows, macos | meeting | meeting-live-notes | high | strong | mixed | 9 | 203 | 3 | Successor of src/meeting_detector.rs and src/meeting_telemetry.rs. Audio-process and UI-scan backend state machines, candidate resolution, shared telemetry, and a scored trajectory eval. ui_scan/macos.rs and ui_scan/windows.rs are cfg-gated and only execute on their target OS; both backends are null on Linux. |+| engine-meeting-watcher | screenpipe-engine | windows, macos | meeting | meeting-live-notes | high | strong | mixed | 9 | 213 | 3 | Successor of src/meeting_detector.rs and src/meeting_telemetry.rs. Audio-process and UI-scan backend state machines, candidate resolution, shared telemetry, and a scored trajectory eval. ui_scan/macos.rs and ui_scan/windows.rs are cfg-gated and only execute on their target OS; both backends are null on Linux. || engine-retention-storage | screenpipe-engine | windows, macos, linux | storage, engine-lifecycle, performance | engine-health-lifecycle, performance-liveness | medium | strong | mixed | 5 | 38 | 0 | Local retention deletion (including lean-mode heavy-text stripping), cloud archive watermarking, atomic state-file replacement, and the low-disk capture monitor. || engine-telemetry-observability | screenpipe-engine | windows, macos, linux | engine-lifecycle, performance | engine-health-lifecycle, performance-liveness | medium | strong | unit | 6 | 29 | 0 | PostHog capture gating, telemetry context shaping, piggyback telemetry forwarding, crash-log helpers, resource monitoring, and the recording-coverage reliability metric. || screen-capture-ocr-contract | screenpipe-screen | windows, macos, linux | vision-capture, ocr | capture-ocr-pipeline | high | partial | unit | 3 | 14 | 0 | Cross-platform cached-OCR unit coverage for RawCaptureResult to CaptureResult metadata, browser URL, focus state, window-to-screen OCR coordinate transformation, Tesseract output parsing, and contour-based text-region detection for the meeting OCR gate. |@@ -370,7 +370,7 @@ bun run coverage:core -- --llvm-cov-summary ../../docs/coverage/core-llvm-cov-su| engine-meeting-privacy-sync | screenpipe-engine | src/meeting_export.rs | source | 7 | 1 | 8 || engine-meeting-watcher | screenpipe-engine | src/meeting_watcher/audio_process/resolve.rs | source | 5 | 0 | 5 || engine-meeting-watcher | screenpipe-engine | src/meeting_watcher/audio_process/state.rs | source | 1 | 0 | 1 |-| engine-meeting-watcher | screenpipe-engine | src/meeting_watcher/audio_process/tests.rs | source | 57 | 0 | 57 |+| engine-meeting-watcher | screenpipe-engine | src/meeting_watcher/audio_process/tests.rs | source | 67 | 0 | 67 || engine-meeting-watcher | screenpipe-engine | src/meeting_watcher/mod.rs | source | 2 | 0 | 2 || engine-meeting-watcher | screenpipe-engine | src/meeting_watcher/shared/telemetry.rs | source | 6 | 0 | 6 || engine-meeting-watcher | screenpipe-engine | src/meeting_watcher/ui_scan/macos.rs | source | 0 | 2 | 2 |@@ -401,7 +401,7 @@ bun run coverage:core -- --llvm-cov-summary ../../docs/coverage/core-llvm-cov-su| engine-api-routes | screenpipe-engine | src/routes/health.rs | source | 34 | 0 | 34 || engine-api-routes | screenpipe-engine | src/routes/live_views.rs | source | 1 | 0 | 1 || engine-api-routes | screenpipe-engine | src/routes/meeting_summary_status.rs | source | 9 | 0 | 9 |-| engine-api-routes | screenpipe-engine | src/routes/meetings.rs | source | 5 | 0 | 5 |+| engine-api-routes | screenpipe-engine | src/routes/meetings.rs | source | 6 | 0 | 6 || engine-api-routes | screenpipe-engine | src/routes/memories.rs | source | 5 | 0 | 5 || engine-api-routes | screenpipe-engine | src/routes/request_origin.rs | source | 1 | 0 | 1 || engine-api-routes | screenpipe-engine | src/routes/response_format.rs | source | 6 | 0 | 6 |