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: assign audio transcriptions to all overlapping frames in timeline

Leigh Phillips0a88af0e8de0
diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rs
index 3c434b936..7f2638790 100644
--- a/crates/screenpipe-db/src/db.rs
+++ b/crates/screenpipe-db/src/db.rs
@@ -2231,28 +2231,70 @@ impl DatabaseManager {
}
// Process audio data with proper synchronization
+ // Audio chunks can span multiple frames, so we assign audio to ALL frames
+ // that fall within the audio's time range (timestamp + start_time to timestamp + end_time)
for row in audio_rows {
- let timestamp: DateTime<Utc> = row.get("timestamp");
+ let audio_timestamp: DateTime<Utc> = row.get("timestamp");
+ let start_offset: Option<f64> = row.try_get("start_time").ok();
+ let end_offset: Option<f64> = row.try_get("end_time").ok();
+
+ // Calculate audio time range
+ // start_time and end_time are offsets in seconds from the audio timestamp
+ let audio_start = if let Some(start) = start_offset {
+ audio_timestamp + chrono::Duration::milliseconds((start * 1000.0) as i64)
+ } else {
+ audio_timestamp
+ };
+
+ let audio_end = if let Some(end) = end_offset {
+ audio_timestamp + chrono::Duration::milliseconds((end * 1000.0) as i64)
+ } else {
+ // If no end_time, use duration_secs to calculate end
+ let duration: f64 = row.try_get("duration_secs").unwrap_or(5.0);
+ audio_timestamp + chrono::Duration::milliseconds((duration * 1000.0) as i64)
+ };
- // Find the closest frame
- if let Some((&key, _)) = frames_map
- .range(..=(timestamp, i64::MAX))
- .next_back()
- .or_else(|| frames_map.iter().next())
- {
+ // Create the audio entry once
+ let audio_entry = AudioEntry {
+ transcription: row.get("transcription"),
+ device_name: row.get("audio_device"),
+ is_input: row.get("is_input_device"),
+ audio_file_path: row.get("audio_path"),
+ duration_secs: row.get("duration_secs"),
+ audio_chunk_id: row.get("audio_chunk_id"),
+ speaker_id: row.try_get("speaker_id").ok(),
+ speaker_name: row.try_get("speaker_name").ok(),
+ start_time: start_offset,
+ end_time: end_offset,
+ };
+
+ // Find ALL frames within the audio time range
+ // First, collect the keys of matching frames (need to collect since we can't mutate while iterating)
+ let matching_keys: Vec<(DateTime<Utc>, i64)> = frames_map
+ .range((audio_start, i64::MIN)..=(audio_end, i64::MAX))
+ .filter(|((frame_ts, _), _)| *frame_ts >= audio_start && *frame_ts <= audio_end)
+ .map(|(key, _)| *key)
+ .collect();
+
+ // Then, add the audio entry to each matching frame
+ let matched_any = !matching_keys.is_empty();
+ for key in matching_keys {
if let Some(frame_data) = frames_map.get_mut(&key) {
- frame_data.audio_entries.push(AudioEntry {
- transcription: row.get("transcription"),
- device_name: row.get("audio_device"),
- is_input: row.get("is_input_device"),
- audio_file_path: row.get("audio_path"),
- duration_secs: row.get("duration_secs"),
- audio_chunk_id: row.get("audio_chunk_id"),
- speaker_id: row.try_get("speaker_id").ok(),
- speaker_name: row.try_get("speaker_name").ok(),
- start_time: row.try_get("start_time").ok(),
- end_time: row.try_get("end_time").ok(),
- });
+ frame_data.audio_entries.push(audio_entry.clone());
+ }
+ }
+
+ // Fallback: If no frames matched (audio outside frame range), assign to closest frame
+ // This handles edge cases where audio timestamp is slightly outside the frame range
+ if !matched_any {
+ if let Some((&key, _)) = frames_map
+ .range(..=(audio_timestamp, i64::MAX))
+ .next_back()
+ .or_else(|| frames_map.iter().next())
+ {
+ if let Some(frame_data) = frames_map.get_mut(&key) {
+ frame_data.audio_entries.push(audio_entry);
+ }
}
}
}
diff --git a/crates/screenpipe-db/src/types.rs b/crates/screenpipe-db/src/types.rs
index e4bafb6f5..cee22f101 100644
--- a/crates/screenpipe-db/src/types.rs
+++ b/crates/screenpipe-db/src/types.rs
@@ -97,6 +97,7 @@ pub struct OCRResult {
#[serde(rename_all = "lowercase")]
pub enum ContentType {
#[default]
+ #[serde(alias = "All")]
All,
/// Screen text from screenshots
OCR,
@@ -573,3 +574,29 @@ pub struct InsertUiEvent {
pub element_bounds: Option<String>,
pub frame_id: Option<i64>,
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_content_type_case_insensitive() {
+ // Test lowercase (original behavior)
+ assert_eq!(ContentType::Audio, serde_json::from_str(r#""audio""#).unwrap());
+ assert_eq!(ContentType::Vision, serde_json::from_str(r#""vision""#).unwrap());
+ assert_eq!(ContentType::Input, serde_json::from_str(r#""input""#).unwrap());
+ assert_eq!(ContentType::All, serde_json::from_str(r#""all""#).unwrap());
+
+ // Test uppercase (new behavior with aliases)
+ assert_eq!(ContentType::Audio, serde_json::from_str(r#""Audio""#).unwrap());
+ assert_eq!(ContentType::Vision, serde_json::from_str(r#""Vision""#).unwrap());
+ assert_eq!(ContentType::Input, serde_json::from_str(r#""Input""#).unwrap());
+ assert_eq!(ContentType::All, serde_json::from_str(r#""All""#).unwrap());
+
+ // Test OCR/UI aliases (both cases)
+ assert_eq!(ContentType::OCR, serde_json::from_str(r#""ocr""#).unwrap());
+ assert_eq!(ContentType::OCR, serde_json::from_str(r#""OCR""#).unwrap());
+ assert_eq!(ContentType::UI, serde_json::from_str(r#""ui""#).unwrap());
+ assert_eq!(ContentType::UI, serde_json::from_str(r#""UI""#).unwrap());
+ }
+}
diff --git a/crates/screenpipe-db/tests/keyword_search_order_test.rs b/crates/screenpipe-db/tests/keyword_search_order_test.rs
index 14f21b774..152c4e807 100644
--- a/crates/screenpipe-db/tests/keyword_search_order_test.rs
+++ b/crates/screenpipe-db/tests/keyword_search_order_test.rs
@@ -2,6 +2,7 @@
mod tests {
use chrono::{Duration, Utc};
use screenpipe_db::{DatabaseManager, OcrEngine, Order};
+ use screenpipe_db::fts_indexer::index_all_tables;
use std::sync::Arc;
async fn setup_test_db() -> DatabaseManager {
@@ -73,6 +74,9 @@ mod tests {
// Frame C: 30 min ago
let _frame_c = insert_frame_with_ocr(&db, "Cursor", "editor", "println hello", 30).await;
+ // Index FTS tables before searching
+ index_all_tables(&db).await;
+
let results = db
.search_with_text_positions(
"hello",
@@ -126,6 +130,9 @@ mod tests {
let _frame_new =
insert_frame_with_ocr(&db, "WezTerm", "terminal", "new content hello world", 5).await;
+ // Index FTS tables before searching
+ index_all_tables(&db).await;
+
let results = db
.search_with_text_positions(
"hello",
@@ -180,6 +187,9 @@ mod tests {
)
.await;
+ // Index FTS tables before searching
+ index_all_tables(&db).await;
+
let results = db
.search_with_text_positions(
"hello",
diff --git a/crates/screenpipe-db/tests/timeline_performance_test.rs b/crates/screenpipe-db/tests/timeline_performance_test.rs
index 0bf01314d..14ab6967e 100644
--- a/crates/screenpipe-db/tests/timeline_performance_test.rs
+++ b/crates/screenpipe-db/tests/timeline_performance_test.rs
@@ -553,6 +553,206 @@ mod timeline_performance_tests {
);
}
+ // =========================================================================
+ // TEST: Multi-frame audio assignment
+ // =========================================================================
+
+ /// Test that audio is assigned to ALL frames within its time range
+ /// This verifies the fix for the timeline scrollbar not flagging transcriptions
+ #[tokio::test]
+ async fn test_audio_assigned_to_multiple_frames() {
+ let db = setup_test_db().await;
+
+ println!("\n=== MULTI-FRAME AUDIO ASSIGNMENT TEST ===");
+
+ // Create frames at 2-second intervals
+ let start_time = Utc::now() - Duration::minutes(5);
+ let frame_count = 10; // 10 frames, 2 seconds apart = 20 seconds of frames
+
+ // Insert video chunk first
+ let _ = db
+ .insert_video_chunk("test_video.mp4", "test_device")
+ .await
+ .unwrap();
+
+ for i in 0..frame_count {
+ let timestamp = start_time + Duration::seconds(i as i64 * 2);
+ let frame_id = db
+ .insert_frame(
+ "test_device",
+ Some(timestamp),
+ None,
+ Some("TestApp"),
+ Some("TestWindow"),
+ false,
+ None,
+ )
+ .await
+ .unwrap();
+
+ db.insert_ocr_text(frame_id, &format!("OCR text for frame {}", i), "", Arc::new(OcrEngine::Tesseract))
+ .await
+ .unwrap();
+ }
+
+ // Insert an audio transcription that spans 6 seconds (should cover ~3 frames)
+ // Audio starts at frame 2's timestamp and ends at frame 5's timestamp
+ let audio_start_time = start_time + Duration::seconds(4); // Frame 2 timestamp
+ let audio_chunk_id = db
+ .insert_audio_chunk("audio_test.mp4", Some(audio_start_time))
+ .await
+ .unwrap();
+
+ // Insert transcription with start_time=0 and end_time=6 (6 seconds duration)
+ // This should match frames 2, 3, and 4 (timestamps at 4s, 6s, 8s from start_time)
+ db.insert_audio_transcription(
+ audio_chunk_id,
+ "This is a test transcription that spans multiple frames",
+ 0,
+ "",
+ &AudioDevice {
+ name: "default".to_string(),
+ device_type: DeviceType::Output,
+ },
+ None,
+ Some(0.0), // start_time offset
+ Some(6.0), // end_time offset (6 seconds)
+ Some(audio_start_time),
+ )
+ .await
+ .unwrap();
+
+ // Query the frames
+ let end_time = start_time + Duration::seconds(30);
+ let result = db.find_video_chunks(start_time, end_time).await.unwrap();
+
+ println!("Total frames: {}", result.frames.len());
+
+ // Count how many frames have audio
+ let frames_with_audio: Vec<_> = result
+ .frames
+ .iter()
+ .filter(|f| !f.audio_entries.is_empty())
+ .collect();
+
+ println!("Frames with audio: {}", frames_with_audio.len());
+
+ for frame in &result.frames {
+ let has_audio = !frame.audio_entries.is_empty();
+ println!(
+ "Frame at {:?}: {} audio entries",
+ frame.timestamp,
+ frame.audio_entries.len()
+ );
+ }
+
+ // Assert that multiple frames have audio
+ // With 6 seconds of audio and frames at 2-second intervals, we expect at least 3 frames
+ assert!(
+ frames_with_audio.len() >= 3,
+ "Expected at least 3 frames to have audio, but only {} did",
+ frames_with_audio.len()
+ );
+
+ // Verify the audio is on the correct frames (frames 2, 3, 4 based on timestamps)
+ let frame_timestamps_with_audio: Vec<_> = frames_with_audio
+ .iter()
+ .map(|f| f.timestamp)
+ .collect();
+
+ let expected_start = audio_start_time;
+ let expected_end = audio_start_time + Duration::seconds(6);
+
+ for frame in &frames_with_audio {
+ assert!(
+ frame.timestamp >= expected_start && frame.timestamp <= expected_end,
+ "Frame at {:?} has audio but is outside expected range [{:?}, {:?}]",
+ frame.timestamp,
+ expected_start,
+ expected_end
+ );
+ }
+ }
+
+ /// Test that audio with no matching frames falls back to closest frame
+ #[tokio::test]
+ async fn test_audio_fallback_to_closest_frame() {
+ let db = setup_test_db().await;
+
+ println!("\n=== AUDIO FALLBACK TEST ===");
+
+ // Create frames at the beginning of the time range
+ let start_time = Utc::now() - Duration::minutes(5);
+
+ let _ = db
+ .insert_video_chunk("test_video.mp4", "test_device")
+ .await
+ .unwrap();
+
+ // Insert 3 frames at the start
+ for i in 0..3 {
+ let timestamp = start_time + Duration::seconds(i as i64 * 2);
+ let frame_id = db
+ .insert_frame(
+ "test_device",
+ Some(timestamp),
+ None,
+ Some("TestApp"),
+ Some("TestWindow"),
+ false,
+ None,
+ )
+ .await
+ .unwrap();
+
+ db.insert_ocr_text(frame_id, &format!("OCR text for frame {}", i), "", Arc::new(OcrEngine::Tesseract))
+ .await
+ .unwrap();
+ }
+
+ // Insert audio that's AFTER all frames (should fall back to closest frame)
+ let audio_time = start_time + Duration::seconds(30); // Way after the frames
+ let audio_chunk_id = db
+ .insert_audio_chunk("audio_late.mp4", Some(audio_time))
+ .await
+ .unwrap();
+
+ db.insert_audio_transcription(
+ audio_chunk_id,
+ "This audio is after all frames",
+ 0,
+ "",
+ &AudioDevice {
+ name: "default".to_string(),
+ device_type: DeviceType::Output,
+ },
+ None,
+ Some(0.0),
+ Some(2.0),
+ Some(audio_time),
+ )
+ .await
+ .unwrap();
+
+ // Query
+ let end_time = start_time + Duration::minutes(10);
+ let result = db.find_video_chunks(start_time, end_time).await.unwrap();
+
+ // At least one frame should have the audio (fallback)
+ let frames_with_audio: Vec<_> = result
+ .frames
+ .iter()
+ .filter(|f| !f.audio_entries.is_empty())
+ .collect();
+
+ println!("Frames with audio (fallback): {}", frames_with_audio.len());
+
+ assert!(
+ !frames_with_audio.is_empty(),
+ "Expected at least one frame to have audio via fallback"
+ );
+ }
+
// =========================================================================
// TEST: Stress test to find breaking point
// =========================================================================
diff --git a/plans/fix-timeline-audio-flagging.md b/plans/fix-timeline-audio-flagging.md
new file mode 100644
index 000000000..759dcdcda
--- /dev/null
+++ b/plans/fix-timeline-audio-flagging.md
@@ -0,0 +1,187 @@
+# Fix: Timeline Scrollbar Not Flagging Transcriptions
+
+## Problem Summary
+
+The timeline scrollbar at the bottom of the page is not consistently showing audio indicators (taller bars) for frames that have transcriptions. While transcriptions exist in the database and can be retrieved via agent search, they are not being properly flagged in the timeline UI.
+
+## Root Cause Analysis
+
+The issue is in the audio-to-frame matching logic in [`find_video_chunks`](../crates/screenpipe-db/src/db.rs:2318) function.
+
+### Current Implementation (Problematic)
+
+```rust
+// Process audio data with proper synchronization
+for row in audio_rows {
+ let timestamp: DateTime<Utc> = row.get("timestamp");
+
+ // Find the closest frame
+ if let Some((&key, _)) = frames_map
+ .range(..=(timestamp, i64::MAX))
+ .next_back()
+ .or_else(|| frames_map.iter().next())
+ {
+ if let Some(frame_data) = frames_map.get_mut(&key) {
+ frame_data.audio_entries.push(AudioEntry { ... });
+ }
+ }
+}
+```
+
+### Issues Identified
+
+1. **Single Frame Assignment**: Audio is only assigned to ONE frame, but audio chunks can span multiple frames (several seconds of audio)
+
+2. **Timestamp Mismatch**: Audio timestamps and frame timestamps are independent:
+ - Frames are captured at screen capture intervals (~0.5-2 seconds)
+ - Audio chunks have their own timestamps with `start_time` and `end_time` offsets
+ - The current logic only matches to the closest frame BEFORE the audio timestamp
+
+3. **No Time Window Tolerance**: The matching logic doesn't account for:
+ - Audio duration (can be 5-30+ seconds per chunk)
+ - Frames that occur DURING the audio playback
+
+4. **BTreeMap Key Structure**: The key `(DateTime<Utc>, i64)` uses `offset_index` as secondary key, making range queries by timestamp alone awkward
+
+## Data Flow
+
+```
+┌─────────────────────────────────────────────────────────────────┐
+│ Database Queries │
+├─────────────────────────────────────────────────────────────────┤
+│ frames_query: Get frames with OCR data │
+│ audio_query: Get audio transcriptions │
+│ │
+│ Both use same time range: start_time to end_time │
+└─────────────────────────────────────────────────────────────────┘
+ │
+ ▼
+┌─────────────────────────────────────────────────────────────────┐
+│ Audio-to-Frame Matching │
+├─────────────────────────────────────────────────────────────────┤
+│ Current: Match audio to single frame closest BEFORE timestamp │
+│ Problem: Audio spans multiple frames, only one gets flagged │
+└─────────────────────────────────────────────────────────────────┘
+ │
+ ▼
+┌─────────────────────────────────────────────────────────────────┐
+│ Timeline Display │
+├─────────────────────────────────────────────────────────────────┤
+│ hasAudio = Boolean(frame?.devices?.[0]?.audio?.length) │
+│ - Taller bars for frames with audio │
+│ - Most frames show no audio even though audio exists │
+└─────────────────────────────────────────────────────────────────┘
+```
+
+## Proposed Solution
+
+### Option A: Multi-Frame Audio Assignment (Recommended)
+
+Assign audio to ALL frames that fall within the audio's time range:
+
+```rust
+// For each audio entry, find ALL frames within its time range
+for row in audio_rows {
+ let audio_timestamp: DateTime<Utc> = row.get("timestamp");
+ let start_offset: f64 = row.try_get("start_time").unwrap_or(0.0);
+ let end_offset: f64 = row.try_get("end_time").unwrap_or(0.0);
+
+ // Calculate audio time range
+ let audio_start = audio_timestamp + chrono::Duration::milliseconds(start_offset as i64 * 1000);
+ let audio_end = audio_timestamp + chrono::Duration::milliseconds(end_offset as i64 * 1000);
+
+ // Find all frames within this range
+ for (&key, frame_data) in frames_map.range((audio_start, i64::MIN)..=(audio_end, i64::MAX)) {
+ frame_data.audio_entries.push(AudioEntry { ... });
+ }
+}
+```
+
+**Pros:**
+- Accurate representation of when audio occurred
+- All relevant frames show audio indicators
+- Better UX for finding audio in timeline
+
+**Cons:**
+- More complex matching logic
+- Potential for duplicate audio entries across frames
+- Need to handle deduplication in UI
+
+### Option B: Time Window Tolerance
+
+Use a time window tolerance when matching audio to frames:
+
+```rust
+const AUDIO_MATCH_WINDOW_SECS: i64 = 30; // 30 second window
+
+for row in audio_rows {
+ let timestamp: DateTime<Utc> = row.get("timestamp");
+ let window_start = timestamp - chrono::Duration::seconds(AUDIO_MATCH_WINDOW_SECS);
+ let window_end = timestamp + chrono::Duration::seconds(AUDIO_MATCH_WINDOW_SECS);
+
+ // Find frames within the window
+ for (&key, frame_data) in frames_map.range((window_start, i64::MIN)..=(window_end, i64::MAX)) {
+ frame_data.audio_entries.push(AudioEntry { ... });
+ }
+}
+```
+
+### Option C: Frontend Fallback (Quick Fix)
+
+Add a fallback in the frontend to check for audio in nearby frames:
+
+```typescript
+// In timeline.tsx
+const hasAudio = useMemo(() => {
+ // Check current frame
+ if (frame?.devices?.[0]?.audio?.length) return true;
+
+ // Check nearby frames (within 30 seconds)
+ const frameTime = new Date(frame.timestamp).getTime();
+ const nearbyFrames = frames.filter(f => {
+ const t = new Date(f.timestamp).getTime();
+ return Math.abs(t - frameTime) < 30000; // 30 seconds
+ });
+
+ return nearbyFrames.some(f => f?.devices?.[0]?.audio?.length);
+}, [frame, frames]);
+```
+
+## Recommended Implementation Plan
+
+### Phase 1: Backend Fix (Option A)
+
+1. **Modify [`find_video_chunks`](../crates/screenpipe-db/src/db.rs:2318)** to assign audio to all frames within the audio's time range
+
+2. **Add deduplication** to prevent the same audio from appearing multiple times in the UI for the same frame
+
+3. **Update tests** to verify multi-frame audio assignment
+
+### Phase 2: Frontend Enhancement
+
+1. **Update timeline tooltip** to show all audio entries for a frame
+
+2. **Add audio duration indicator** to show how long the audio spans
+
+3. **Consider visual indicator** for frames with long audio vs short audio
+
+## Files to Modify
+
+1. `crates/screenpipe-db/src/db.rs` - Audio-to-frame matching logic
+2. `crates/screenpipe-server/src/routes/streaming.rs` - Audio entry creation
+3. `apps/screenpipe-app-tauri/components/rewind/timeline/timeline.tsx` - Frontend display (optional enhancement)
+
+## Testing Plan
+
+1. **Unit Tests**: Add tests for multi-frame audio assignment
+2. **Integration Tests**: Verify audio appears on correct frames in timeline
+3. **Manual Testing**:
+ - Record screen with audio
+ - Verify timeline shows audio indicators on all relevant frames
+ - Check that clicking a frame with audio shows the transcription
+
+## Estimated Effort
+
+- Backend changes: Moderate complexity
+- Testing: Moderate
+- Frontend enhancements: Low (optional)