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

fix: speaker reassignment majority-vote + optimistic UI + undo

Louis Beaumont63424a0ba647
diff --git a/apps/screenpipe-app-tauri/components/speaker-assign-popover.tsx b/apps/screenpipe-app-tauri/components/speaker-assign-popover.tsx
index 897f6dd77..ab9c0af8b 100644
--- a/apps/screenpipe-app-tauri/components/speaker-assign-popover.tsx
+++ b/apps/screenpipe-app-tauri/components/speaker-assign-popover.tsx
@@ -11,6 +11,7 @@ import { SpeakerBadge } from "@/components/speaker-badge";
import { useToast } from "@/components/ui/use-toast";
import { Check, Ghost, Loader2, Plus, Volume2 } from "lucide-react";
import { VideoComponent } from "@/components/rewind/video";
+import { ToastAction } from "@/components/ui/toast";
import { cn } from "@/lib/utils";
interface Speaker {
@@ -83,14 +84,17 @@ export function SpeakerAssignPopover({
if (!name.trim()) return;
setIsAssigning(true);
+ const trimmedName = name.trim();
+
try {
+ // Phase 1: Assign just this chunk instantly (no propagation)
const response = await fetch("http://localhost:3030/speakers/reassign", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
audio_chunk_id: audioChunkId,
- new_speaker_name: name.trim(),
- propagate_similar: true,
+ new_speaker_name: trimmedName,
+ propagate_similar: false,
}),
});
@@ -99,14 +103,75 @@ export function SpeakerAssignPopover({
}
const result = await response.json();
- toast({
- title: "Speaker assigned",
- description: `Assigned to "${name}". ${result.embeddings_moved} similar voices updated.`,
- });
+ // Close popover immediately — this chunk is assigned
onAssigned?.(result.new_speaker_id, result.new_speaker_name);
setOpen(false);
setSearchTerm("");
+ setIsAssigning(false);
+
+ toast({
+ title: `assigned to "${trimmedName}"`,
+ description: "propagating to similar voices...",
+ });
+
+ // Phase 2: Propagate in background (non-blocking)
+ try {
+ const propagateResponse = await fetch("http://localhost:3030/speakers/reassign", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ audio_chunk_id: audioChunkId,
+ new_speaker_name: trimmedName,
+ propagate_similar: true,
+ }),
+ });
+
+ if (propagateResponse.ok) {
+ const propagateResult = await propagateResponse.json();
+ const oldAssignments: Array<{transcription_id: number, old_speaker_id: number}> = propagateResult.old_assignments || [];
+ const extraMoved = propagateResult.embeddings_moved || 0;
+
+ if (extraMoved > 0) {
+ toast({
+ title: `found ${extraMoved} similar voices`,
+ description: "click undo if incorrect",
+ action: (
+ <ToastAction
+ altText="Undo speaker assignment"
+ onClick={async () => {
+ try {
+ const undoResp = await fetch("http://localhost:3030/speakers/undo-reassign", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ old_assignments: oldAssignments }),
+ });
+ if (undoResp.ok) {
+ const undoResult = await undoResp.json();
+ toast({
+ title: "undone",
+ description: `restored ${undoResult.restored} transcriptions`,
+ });
+ }
+ } catch {
+ toast({ title: "undo failed", variant: "destructive" });
+ }
+ }}
+ >
+ undo
+ </ToastAction>
+ ),
+ });
+ } else {
+ toast({
+ title: `assigned to "${trimmedName}"`,
+ description: "no additional similar voices found",
+ });
+ }
+ }
+ } catch (propagateError) {
+ console.error("Background propagation failed:", propagateError);
+ }
} catch (error) {
console.error("Error assigning speaker:", error);
toast({
@@ -114,7 +179,6 @@ export function SpeakerAssignPopover({
description: "Failed to assign speaker. Please try again.",
variant: "destructive",
});
- } finally {
setIsAssigning(false);
}
},
diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rs
index 20535a80c..228076797 100644
--- a/crates/screenpipe-db/src/db.rs
+++ b/crates/screenpipe-db/src/db.rs
@@ -17,7 +17,7 @@ use sqlx::ValueRef;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
-use tracing::{debug, error, warn};
+use tracing::{debug, error, info, warn};
use std::collections::BTreeMap;
@@ -3343,23 +3343,24 @@ LIMIT ? OFFSET ?
Ok(results)
}
- /// Reassign a speaker: move transcriptions and embeddings to a new or existing speaker
- /// This is the main function for the correction flow
- /// Returns (new_speaker_id, transcriptions_updated, embeddings_moved)
+ /// Reassign a speaker: move transcriptions and embeddings to a new or existing speaker.
+ /// Phase 1 (instant): reassigns just this one audio chunk.
+ /// Phase 2-3 (propagation): majority-vote — only absorbs a speaker if >50% of its
+ /// embeddings match the target. Prevents one similar embedding from stealing all
+ /// transcriptions from an unrelated speaker.
+ /// Returns (new_speaker_id, transcriptions_updated, embeddings_moved, old_assignments)
pub async fn reassign_speaker(
&self,
audio_chunk_id: i64,
new_speaker_name: &str,
propagate_similar: bool,
- ) -> Result<(i64, u64, u64), sqlx::Error> {
- // Phase 1: Short IMMEDIATE write transaction – reassign the chunk and move one embedding.
- // Uses BEGIN IMMEDIATE to acquire write lock upfront (avoids SQLITE_BUSY_SNAPSHOT
- // code 517 that happens with DEFERRED transactions in WAL mode under contention).
- // Retries on busy errors since the recording pipeline writes constantly.
+ ) -> Result<(i64, u64, u64, Vec<(i64, i64)>), sqlx::Error> {
+ let mut old_assignments: Vec<(i64, i64)> = Vec::new();
+
+ // Phase 1: Short IMMEDIATE write transaction – reassign just this chunk.
let (current_speaker_id, target_speaker_id, transcriptions_updated, mut embeddings_moved) = {
let mut tx = self.begin_immediate_with_retry().await?;
- // 1. Get the current speaker_id for this audio chunk
let current_speaker_id: Option<i64> = sqlx::query_scalar(
"SELECT speaker_id FROM audio_transcriptions WHERE audio_chunk_id = ? LIMIT 1",
)
@@ -3372,7 +3373,6 @@ LIMIT ? OFFSET ?
None => return Err(sqlx::Error::RowNotFound),
};
- // 2. Find or create the target speaker
let target_speaker: Speaker = match sqlx::query_as::<_, Speaker>(
"SELECT id, name, metadata FROM speakers WHERE name = ? AND hallucination = 0",
)
@@ -3396,7 +3396,15 @@ LIMIT ? OFFSET ?
}
};
- // 3. Update the transcription's speaker_id
+ // Record old assignments for undo
+ let affected_rows: Vec<(i64, i64)> = sqlx::query_as(
+ "SELECT id, speaker_id FROM audio_transcriptions WHERE audio_chunk_id = ?",
+ )
+ .bind(audio_chunk_id)
+ .fetch_all(&mut **tx.conn())
+ .await?;
+ old_assignments.extend(affected_rows);
+
let transcriptions_updated = sqlx::query(
"UPDATE audio_transcriptions SET speaker_id = ? WHERE audio_chunk_id = ?",
)
@@ -3406,7 +3414,6 @@ LIMIT ? OFFSET ?
.await?
.rows_affected();
- // 4. Move the embedding from old speaker to new speaker
let embedding_id: Option<i64> = sqlx::query_scalar(
"SELECT id FROM speaker_embeddings WHERE speaker_id = ? LIMIT 1",
)
@@ -3433,68 +3440,83 @@ LIMIT ? OFFSET ?
)
};
- // Phase 2: If propagate_similar, do the expensive vector similarity search
- // OUTSIDE any transaction so we don't hold a write lock.
+ // Phase 2: Majority-vote propagation — only absorb speakers where >50% of
+ // their embeddings are similar to target.
if propagate_similar {
- let threshold = 0.8; // Match the hybrid speaker clustering threshold
+ let threshold = 0.8;
+ let min_absorption_ratio = 0.5;
- // Read-only: find similar embeddings from other speakers
- let similar_rows: Vec<(i64, i64)> = sqlx::query(
+ let speaker_match_stats: Vec<(i64, i64, i64)> = sqlx::query_as(
r#"
- SELECT se2.id as embedding_id, se2.speaker_id
+ SELECT
+ se2.speaker_id,
+ COUNT(DISTINCT CASE
+ WHEN vec_distance_cosine(se1.embedding, se2.embedding) < ?2
+ THEN se2.id
+ END) as matching_count,
+ (SELECT COUNT(*) FROM speaker_embeddings WHERE speaker_id = se2.speaker_id) as total_count
FROM speaker_embeddings se1
JOIN speaker_embeddings se2 ON se1.speaker_id != se2.speaker_id
- WHERE se1.speaker_id = ?
- AND vec_distance_cosine(se1.embedding, se2.embedding) < ?
- AND se2.speaker_id != ?
+ WHERE se1.speaker_id = ?1
+ AND se2.speaker_id != ?1
+ GROUP BY se2.speaker_id
"#,
)
.bind(target_speaker_id)
.bind(threshold)
- .bind(target_speaker_id)
.fetch_all(&self.pool)
- .await?
- .iter()
- .map(|row| {
- let emb_id: i64 = row.get("embedding_id");
- let old_speaker_id: i64 = row.get("speaker_id");
- (emb_id, old_speaker_id)
- })
- .collect();
+ .await?;
+
+ let speakers_to_absorb: Vec<i64> = speaker_match_stats
+ .iter()
+ .filter(|(_, matching, total)| {
+ *total > 0 && (*matching as f64 / *total as f64) > min_absorption_ratio
+ })
+ .map(|(speaker_id, _, _)| *speaker_id)
+ .collect();
+
+ if !speakers_to_absorb.is_empty() {
+ info!(
+ "speaker reassign: absorbing {} speakers into {} ({})",
+ speakers_to_absorb.len(),
+ target_speaker_id,
+ new_speaker_name
+ );
- // Phase 3: Short IMMEDIATE write transaction – apply the similarity results.
- if !similar_rows.is_empty() {
let mut tx = self.begin_immediate_with_retry().await?;
- for (emb_id, old_speaker_id) in &similar_rows {
- sqlx::query("UPDATE speaker_embeddings SET speaker_id = ? WHERE id = ?")
- .bind(target_speaker_id)
- .bind(emb_id)
- .execute(&mut **tx.conn())
- .await?;
- embeddings_moved += 1;
+ for old_speaker_id in &speakers_to_absorb {
+ // Record old assignments for undo
+ let affected: Vec<(i64, i64)> = sqlx::query_as(
+ "SELECT id, speaker_id FROM audio_transcriptions WHERE speaker_id = ?",
+ )
+ .bind(old_speaker_id)
+ .fetch_all(&mut **tx.conn())
+ .await?;
+ old_assignments.extend(affected);
- sqlx::query(
- "UPDATE audio_transcriptions SET speaker_id = ? WHERE speaker_id = ?",
+ let moved = sqlx::query(
+ "UPDATE speaker_embeddings SET speaker_id = ? WHERE speaker_id = ?",
)
.bind(target_speaker_id)
.bind(old_speaker_id)
.execute(&mut **tx.conn())
- .await?;
+ .await?
+ .rows_affected();
+ embeddings_moved += moved;
- let remaining: i64 = sqlx::query_scalar(
- "SELECT COUNT(*) FROM speaker_embeddings WHERE speaker_id = ?",
+ sqlx::query(
+ "UPDATE audio_transcriptions SET speaker_id = ? WHERE speaker_id = ?",
)
+ .bind(target_speaker_id)
.bind(old_speaker_id)
- .fetch_one(&mut **tx.conn())
+ .execute(&mut **tx.conn())
.await?;
- if remaining == 0 {
- sqlx::query("DELETE FROM speakers WHERE id = ?")
- .bind(old_speaker_id)
- .execute(&mut **tx.conn())
- .await?;
- }
+ sqlx::query("DELETE FROM speakers WHERE id = ?")
+ .bind(old_speaker_id)
+ .execute(&mut **tx.conn())
+ .await?;
}
tx.commit().await?;
@@ -3519,7 +3541,49 @@ LIMIT ? OFFSET ?
}
}
- Ok((target_speaker_id, transcriptions_updated, embeddings_moved))
+ Ok((target_speaker_id, transcriptions_updated, embeddings_moved, old_assignments))
+ }
+
+ /// Undo a speaker reassignment using the old_assignments from reassign_speaker
+ pub async fn undo_speaker_reassign(
+ &self,
+ old_assignments: &[(i64, i64)],
+ ) -> Result<u64, sqlx::Error> {
+ if old_assignments.is_empty() {
+ return Ok(0);
+ }
+
+ let mut tx = self.begin_immediate_with_retry().await?;
+ let mut restored = 0u64;
+
+ for (transcription_id, old_speaker_id) in old_assignments {
+ let exists: bool = sqlx::query_scalar(
+ "SELECT EXISTS(SELECT 1 FROM speakers WHERE id = ?)",
+ )
+ .bind(old_speaker_id)
+ .fetch_one(&mut **tx.conn())
+ .await?;
+
+ if !exists {
+ sqlx::query("INSERT INTO speakers (id, name) VALUES (?, '')")
+ .bind(old_speaker_id)
+ .execute(&mut **tx.conn())
+ .await?;
+ }
+
+ let affected = sqlx::query(
+ "UPDATE audio_transcriptions SET speaker_id = ? WHERE id = ?",
+ )
+ .bind(old_speaker_id)
+ .bind(transcription_id)
+ .execute(&mut **tx.conn())
+ .await?
+ .rows_affected();
+ restored += affected;
+ }
+
+ tx.commit().await?;
+ Ok(restored)
}
// ============================================================================
diff --git a/crates/screenpipe-server/src/server.rs b/crates/screenpipe-server/src/server.rs
index d8913ccc4..5b40133b1 100644
--- a/crates/screenpipe-server/src/server.rs
+++ b/crates/screenpipe-server/src/server.rs
@@ -226,12 +226,29 @@ fn default_propagate_similar() -> bool {
true
}
+#[derive(OaSchema, Serialize, Deserialize, Debug, Clone)]
+pub struct SpeakerOldAssignment {
+ pub transcription_id: i64,
+ pub old_speaker_id: i64,
+}
+
#[derive(OaSchema, Serialize, Debug)]
pub struct ReassignSpeakerResponse {
pub new_speaker_id: i64,
pub new_speaker_name: String,
pub transcriptions_updated: u64,
pub embeddings_moved: u64,
+ pub old_assignments: Vec<SpeakerOldAssignment>,
+}
+
+#[derive(OaSchema, Serialize, Deserialize, Debug)]
+pub struct UndoSpeakerReassignRequest {
+ pub old_assignments: Vec<SpeakerOldAssignment>,
+}
+
+#[derive(OaSchema, Serialize, Debug)]
+pub struct UndoSpeakerReassignResponse {
+ pub restored: u64,
}
#[derive(OaSchema, Serialize, Deserialize, Debug)]
@@ -375,6 +392,9 @@ pub struct HealthCheckResponse {
pub message: String,
pub verbose_instructions: Option<String>,
pub device_status_details: Option<String>,
+ /// Active monitor names (e.g. ["Built-in Retina Display"])
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub monitors: Option<Vec<String>>,
}
#[derive(OaSchema, Serialize, Deserialize, Clone)]
@@ -954,6 +974,19 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
)
};
+ // Collect monitor names for tray display
+ let monitor_names: Option<Vec<String>> = if !state.vision_disabled {
+ match list_monitors_detailed().await {
+ Ok(monitors) => {
+ let names: Vec<String> = monitors.iter().map(|m| m.name().to_string()).collect();
+ if names.is_empty() { None } else { Some(names) }
+ }
+ Err(_) => None,
+ }
+ } else {
+ None
+ };
+
JsonResponse(HealthCheckResponse {
status: overall_status.to_string(),
status_code,
@@ -971,6 +1004,7 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
message,
verbose_instructions,
device_status_details,
+ monitors: monitor_names,
})
}
@@ -1174,6 +1208,7 @@ impl SCServer {
.post("/speakers/merge", merge_speakers_handler)
.get("/speakers/similar", get_similar_speakers_handler)
.post("/speakers/reassign", reassign_speaker_handler)
+ .post("/speakers/undo-reassign", undo_speaker_reassign_handler)
.post("/experimental/frames/merge", merge_frames_handler)
.get("/experimental/validate/media", validate_media_handler)
.post("/audio/start", start_audio)
@@ -1870,7 +1905,7 @@ async fn reassign_speaker_handler(
State(state): State<Arc<AppState>>,
Json(payload): Json<ReassignSpeakerRequest>,
) -> Result<JsonResponse<ReassignSpeakerResponse>, (StatusCode, JsonResponse<Value>)> {
- let (new_speaker_id, transcriptions_updated, embeddings_moved) = state
+ let (new_speaker_id, transcriptions_updated, embeddings_moved, old_assignments) = state
.db
.reassign_speaker(
payload.audio_chunk_id,
@@ -1890,9 +1925,40 @@ async fn reassign_speaker_handler(
new_speaker_name: payload.new_speaker_name,
transcriptions_updated,
embeddings_moved,
+ old_assignments: old_assignments
+ .into_iter()
+ .map(|(tid, sid)| SpeakerOldAssignment {
+ transcription_id: tid,
+ old_speaker_id: sid,
+ })
+ .collect(),
}))
}
+async fn undo_speaker_reassign_handler(
+ State(state): State<Arc<AppState>>,
+ Json(payload): Json<UndoSpeakerReassignRequest>,
+) -> Result<JsonResponse<UndoSpeakerReassignResponse>, (StatusCode, JsonResponse<Value>)> {
+ let tuples: Vec<(i64, i64)> = payload
+ .old_assignments
+ .iter()
+ .map(|a| (a.transcription_id, a.old_speaker_id))
+ .collect();
+
+ let restored = state
+ .db
+ .undo_speaker_reassign(&tuples)
+ .await
+ .map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": e.to_string()})),
+ )
+ })?;
+
+ Ok(JsonResponse(UndoSpeakerReassignResponse { restored }))
+}
+
// #[derive(OaSchema, Deserialize)]
// pub struct AudioDeviceControlRequest {
// device_name: String,