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
refactor: make timeline a timeseries data structure for efficiency
Louis Beaumont3c2010ef10ad
diff --git a/screenpipe-app-tauri/app/timeline/page.tsx b/screenpipe-app-tauri/app/timeline/page.tsxindex 866eabf17..9202983bd 100644--- a/screenpipe-app-tauri/app/timeline/page.tsx+++ b/screenpipe-app-tauri/app/timeline/page.tsx@@ -18,14 +18,33 @@ import { Input } from "@/components/ui/input";import { Button } from "@/components/ui/button";import { platform } from "@tauri-apps/plugin-os";-interface StreamFramesResponse {- frame: string;+interface StreamTimeSeriesResponse {timestamp: string;+ devices: DeviceFrameResponse[];+}++interface DeviceFrameResponse {+ device_id: string;+ frame: string; // base64 encoded image+ metadata: DeviceMetadata;+ audio: AudioData[];+}++interface DeviceMetadata {file_path: string;- app_name?: string;- window_name?: string;- ocr_text?: string;- transcription?: string;+ app_name: string;+ window_name: string;+ ocr_text: string;+ timestamp: string;+}++interface AudioData {+ device_name: string;+ is_input: boolean;+ transcription: string;+ audio_file_path: string;+ duration_secs: number;+ start_offset: number;}interface TimeRange {@@ -34,10 +53,8 @@ interface TimeRange {}export default function Timeline() {- const [currentFrame, setCurrentFrame] = useState<StreamFramesResponse | null>(- null- );- const [frames, setFrames] = useState<StreamFramesResponse[]>([]);+ const [currentFrame, setCurrentFrame] = useState<DeviceFrameResponse | null>(null);+ const [frames, setFrames] = useState<StreamTimeSeriesResponse[]>([]);const [currentIndex, setCurrentIndex] = useState(0);const [isLoading, setIsLoading] = useState(true);const [error, setError] = useState<string | null>(null);@@ -79,15 +96,12 @@ export default function Timeline() {eventSourceRef.current.close();}- // now minus 2 minutesconst endTime = new Date();endTime.setMinutes(endTime.getMinutes() - 2);- // at 00.01 am todayconst startTime = new Date();startTime.setHours(0, 1, 0, 0);const url = `http://localhost:3030/stream/frames?start_time=${startTime.toISOString()}&end_time=${endTime.toISOString()}&order=descending`;- // Set the initial loaded time rangesetLoadedTimeRange({start: startTime,end: endTime,@@ -100,26 +114,31 @@ export default function Timeline() {eventSource.onmessage = (event) => {try {- const frame = JSON.parse(event.data);- if (frame === "keep-alive-text" || !frame.frame) return;-- setFrames((prev) => {- // Deduplicate frames based on timestamp- const exists = prev.some((f) => f.timestamp === frame.timestamp);- if (exists) return prev;- return [...prev, frame];- });-- // Only set current frame and loading state if it's our first frame- setCurrentFrame((prev) => prev || frame);- setIsLoading(false);+ const data = JSON.parse(event.data);+ if (data === "keep-alive-text") return;++ if (data.timestamp && data.devices) {+ setFrames((prev) => {+ const exists = prev.some((f) => f.timestamp === data.timestamp);+ if (exists) return prev;++ // ! HACK: Add new frame and sort in descending order+ const newFrames = [...prev, data].sort((a, b) => {+ return new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime();+ });++ return newFrames;+ });++ setCurrentFrame((prev) => prev || data.devices[0]);+ setIsLoading(false);+ }} catch (error) {console.error("failed to parse frame data:", error);}};eventSource.onerror = (error) => {- // Ignore end of stream errors (expected behavior)if (eventSource.readyState === EventSource.CLOSED) {console.log("stream ended (expected behavior)", error);setIsLoading(false);@@ -140,24 +159,40 @@ export default function Timeline() {};const getLoadedTimeRangeStyles = () => {- if (!loadedTimeRange) return { left: "0%", right: "100%" };+ if (!loadedTimeRange || frames.length === 0) return { left: "0%", right: "100%" };++ // Find the earliest frame timestamp+ const firstFrame = [...frames].sort((a, b) =>+ new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()+ )[0];+ const earliestTime = new Date(firstFrame.timestamp);+ // Create local date objects for todayconst startOfDay = new Date();startOfDay.setHours(0, 0, 0, 0);+const endOfDay = new Date();endOfDay.setHours(23, 59, 59, 999);+ // Convert UTC loadedTimeRange to local time+ const localStart = new Date(earliestTime);+ const localEnd = new Date(loadedTimeRange.end);+const totalMs = endOfDay.getTime() - startOfDay.getTime();- const startPercent =- ((loadedTimeRange.start.getTime() - startOfDay.getTime()) / totalMs) *- 100;- const endPercent =- ((loadedTimeRange.end.getTime() - startOfDay.getTime()) / totalMs) * 100;+ const startPercent = ((localStart.getTime() - startOfDay.getTime()) / totalMs) * 100;+ const endPercent = ((localEnd.getTime() - startOfDay.getTime()) / totalMs) * 100;+ // Temporarily return empty values to disable grey areasreturn {- left: `${startPercent}%`,- right: `${100 - endPercent}%`,+ right: "0%",+ left: "0%",};++ // Original code commented out:+ // return {+ // right: `${Math.max(0, Math.min(100, startPercent))}%`, // Grey before data starts+ // left: `${Math.max(0, Math.min(100, 100 - endPercent))}%`, // Grey after data ends+ // };};useEffect(() => {@@ -179,7 +214,6 @@ export default function Timeline() {useEffect(() => {const handleKeyDown = (e: KeyboardEvent) => {- // Cmd+K (Mac) or Ctrl+K (Windows/Linux) to open AI panelif ((e.metaKey || e.ctrlKey) && e.key === "k") {e.preventDefault();if (selectionRange) {@@ -187,7 +221,6 @@ export default function Timeline() {}}- // Cmd+Enter or Ctrl+Enter to send messageif ((e.metaKey || e.ctrlKey) && e.key === "Enter") {e.preventDefault();if (isAiPanelExpanded && aiInput.trim()) {@@ -201,10 +234,8 @@ export default function Timeline() {}, [selectionRange, isAiPanelExpanded, aiInput]);const handleScroll = (e: React.WheelEvent<HTMLDivElement>) => {- // Check if the event originated from within the AI panelconst isWithinAiPanel = aiPanelRef.current?.contains(e.target as Node);if (isWithinAiPanel) {- // Allow normal scrolling behavior for AI panelreturn;}@@ -224,40 +255,44 @@ export default function Timeline() {if (newIndex !== currentIndex) {setCurrentIndex(newIndex);- setCurrentFrame(frames[newIndex]);+ setCurrentFrame(frames[newIndex].devices[0]);}};const getCurrentTimePercentage = () => {- const now = new Date();- const startOfDay = new Date(now);+ if (!currentFrame) return 0;++ const frameTime = new Date(currentFrame.metadata.timestamp || frames[currentIndex].timestamp);+ const startOfDay = new Date(frameTime);startOfDay.setHours(0, 0, 0, 0);- const endOfDay = new Date(now);+ const endOfDay = new Date(frameTime);endOfDay.setHours(23, 59, 59, 999);const totalDayMilliseconds = endOfDay.getTime() - startOfDay.getTime();- const currentMilliseconds = now.getTime() - startOfDay.getTime();+ const currentMilliseconds = frameTime.getTime() - startOfDay.getTime();return (currentMilliseconds / totalDayMilliseconds) * 100;};const handleTimelineMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {const rect = e.currentTarget.getBoundingClientRect();- const percentage = ((e.clientX - rect.left) / rect.width) * 100;+ const clickX = e.clientX - rect.left;+ const percentage = (clickX / rect.width) * 100;++ // Clamp percentage between 0 and 100+ const clampedPercentage = Math.max(0, Math.min(100, percentage));+setIsDragging(true);- setDragStart(percentage);+ setDragStart(clampedPercentage);- // Calculate time in local timezoneconst totalMinutesInDay = 24 * 60;- const minutesFromMidnight = (percentage / 100) * totalMinutesInDay;+ const minutesFromMidnight = (clampedPercentage / 100) * totalMinutesInDay;const hours = Math.floor(minutesFromMidnight / 60);const minutes = Math.floor(minutesFromMidnight % 60);- // Create date in local timeconst localDate = new Date();localDate.setHours(hours, minutes, 0, 0);- // Convert to UTC for storageconst utcDate = new Date(Date.UTC(localDate.getUTCFullYear(),@@ -280,16 +315,16 @@ export default function Timeline() {if (!isDragging || dragStart === null) return;const rect = e.currentTarget.getBoundingClientRect();- const percentage = ((e.clientX - rect.left) / rect.width) * 100;+ const moveX = e.clientX - rect.left;+ const percentage = (moveX / rect.width) * 100;++ // Clamp percentage between 0 and 100+ const clampedPercentage = Math.max(0, Math.min(100, percentage));- // Calculate times for both points in local timeconst totalMinutesInDay = 24 * 60;- const startMinutes =- (Math.min(dragStart, percentage) / 100) * totalMinutesInDay;- const endMinutes =- (Math.max(dragStart, percentage) / 100) * totalMinutesInDay;+ const startMinutes = (Math.min(dragStart, clampedPercentage) / 100) * totalMinutesInDay;+ const endMinutes = (Math.max(dragStart, clampedPercentage) / 100) * totalMinutesInDay;- // Create local datesconst startLocal = new Date();startLocal.setHours(Math.floor(startMinutes / 60),@@ -306,7 +341,6 @@ export default function Timeline() {0);- // Convert to UTC for storageconst utcStartDate = new Date(Date.UTC(startLocal.getUTCFullYear(),@@ -343,15 +377,12 @@ export default function Timeline() {const handleAskAI = () => {if (isAiPanelExpanded) {- // If panel is already open, clear messages and closesetChatMessages([]);setIsAiPanelExpanded(false);setAiInput("");} else {- // Opening fresh panel - always expand directly to chatsetChatMessages([]);setIsAiPanelExpanded(true);- // Focus the input after a brief delay to allow animation to completesetTimeout(() => {inputRef.current?.focus();}, 100);@@ -362,21 +393,16 @@ export default function Timeline() {e.preventDefault();if (!aiInput.trim() || !selectionRange) return;- console.log("Selection range (UTC):", {- start: selectionRange.start.toISOString(),- end: selectionRange.end.toISOString(),- });-+ console.log("selectionRange", selectionRange);+ console.log("frames", frames);const relevantFrames = frames.filter((frame) => {const frameTime = new Date(frame.timestamp);- // console.log("frameTime", frameTime);+ console.log("frameTime", frameTime);return (frameTime >= selectionRange.start && frameTime <= selectionRange.end);});-- console.log("Total frames:", frames.length);- console.log("Relevant frames:", relevantFrames);+ console.log("relevantFrames", relevantFrames);const userMessage = {id: generateId(),@@ -414,10 +440,11 @@ export default function Timeline() {content: `Context data: ${JSON.stringify(relevantFrames.map((frame) => ({timestamp: frame.timestamp,- app_name: frame.app_name,- window_name: frame.window_name,- ocr_text: frame.ocr_text,- transcription: frame.transcription,+ devices: frame.devices.map(device => ({+ device_id: device.device_id,+ metadata: device.metadata,+ audio: device.audio,+ }))})))}@@ -471,10 +498,8 @@ export default function Timeline() {}};- // Add this to prevent scroll on the documentuseEffect(() => {const preventScroll = (e: WheelEvent) => {- // Check if the event target is within the AI panelconst isWithinAiPanel = aiPanelRef.current?.contains(e.target as Node);if (!isWithinAiPanel) {e.preventDefault();@@ -545,7 +570,6 @@ export default function Timeline() {<divclassName="fixed inset-0 flex flex-col bg-black text-white overflow-hidden font-['Press_Start_2P'] relative"onWheel={(e) => {- // Only handle wheel events if they're not from the AI panelconst isWithinAiPanel = aiPanelRef.current?.contains(e.target as Node);if (!isWithinAiPanel) {handleScroll(e);@@ -567,7 +591,6 @@ export default function Timeline() {<RotateCcw className="h-4 w-4" /></button>- {/* Scanline effect overlay */}<divclassName="fixed inset-0 pointer-events-none z-50"style={{@@ -576,7 +599,6 @@ export default function Timeline() {}}/>- {/* Frame viewer */}<div className="flex-1 relative min-h-0">{isLoading && (<div className="absolute inset-0 flex items-center justify-center">@@ -593,15 +615,12 @@ export default function Timeline() {)}{currentFrame && (<>- {/* App info centered above frame */}<div className="w-4/5 mx-auto mt-4 mb-4 text-center select-none"><div className="inline-block bg-black/50 p-2 rounded shadow-lg backdrop-blur-sm border border-[#333] text-[#888] text-xs tracking-wider"><div className="flex items-center gap-4">- <div>- {new Date(currentFrame?.timestamp).toLocaleTimeString()}- </div>- <div>app: {currentFrame?.app_name || "n/a"}</div>- <div>window: {currentFrame?.window_name || "n/a"}</div>+ <div>device: {currentFrame.device_id}</div>+ <div>app: {currentFrame.metadata.app_name || "n/a"}</div>+ <div>window: {currentFrame.metadata.window_name || "n/a"}</div></div></div></div>@@ -614,7 +633,6 @@ export default function Timeline() {)}</div>- {/* Timeline bar */}<div className="w-4/5 mx-auto my-8 relative select-none"><divclassName="h-[60px] bg-[#111] border-4 border-[#444] shadow-[0_0_16px_rgba(0,0,0,0.8),inset_0_0_8px_rgba(255,255,255,0.1)] cursor-crosshair relative"@@ -623,7 +641,6 @@ export default function Timeline() {onMouseUp={handleTimelineMouseUp}onMouseLeave={handleTimelineMouseUp}>- {/* Unloaded regions overlay - making it more visible with a different color and opacity */}<divclassName="absolute inset-0 pointer-events-none"style={{@@ -633,7 +650,6 @@ export default function Timeline() {}}/>- {/* Grid lines */}<divclassName="absolute inset-0"style={{@@ -643,7 +659,6 @@ export default function Timeline() {}}/>- {/* Current position indicator */}<divclassName="absolute top-0 h-full w-1 bg-[#0f0] shadow-[0_0_12px_#0f0] opacity-80 z-10"style={{@@ -651,7 +666,6 @@ export default function Timeline() {}}/>- {/* Selection overlay */}{selectionRange && (<divclassName="absolute top-0 h-full bg-[#0f0] opacity-20"@@ -672,7 +686,6 @@ export default function Timeline() {)}</div>- {/* Floating window when selection exists */}{selectionRange && (<divref={aiPanelRef}@@ -698,7 +711,6 @@ export default function Timeline() {<div className="flex items-center gap-2 flex-1 cursor-grab active:cursor-grabbing"><GripHorizontal className="w-4 h-4 text-[#0f0]/50 group-hover:text-[#0f0]" /><div className="text-[#0f0] text-xs">- {/* Convert UTC to local for display */}{new Date(selectionRange.start.getTime()).toLocaleTimeString()}{" "}@@ -710,8 +722,8 @@ export default function Timeline() {onClick={() => {setSelectionRange(null);setIsAiPanelExpanded(false);- setChatMessages([]); // Clear messages- setAiInput(""); // Clear input+ setChatMessages([]);+ setAiInput("");}}className="text-[#0f0] hover:text-[#0f0]/70 ml-2">@@ -740,7 +752,6 @@ export default function Timeline() {{isAiPanelExpanded && (<div className="flex flex-col h-[calc(100%-100px)]">- {/* Chat messages - Fixed height and scrollable */}<divclassName="flex-1 overflow-y-auto p-4 space-y-4 min-h-0 hover:cursor-auto text-[#eee] font-mono text-sm leading-relaxed"style={{@@ -763,7 +774,6 @@ export default function Timeline() {)}</div>- {/* Input form */}<formonSubmit={handleAiSubmit}className="p-4 border-t border-[#0f0]/20"@@ -807,12 +817,11 @@ export default function Timeline() {</div>)}- {/* Timeline timestamps */}<div className="relative mt-1 px-2 text-[10px] text-[#0f0] shadow-[0_0_8px_#0f0] select-none">{Array(7).fill(0).map((_, i) => {- const hour = (i * 4) % 24; // Start at 0 and increment by 4 hours+ const hour = (i * 4) % 24;const date = new Date();date.setHours(hour, 0, 0, 0);return (@@ -831,7 +840,6 @@ export default function Timeline() {</div></div>- {/* Scroll indicator */}<div className="fixed left-12 top-1/2 -translate-y-1/2 font-['Press_Start_2P'] text-xs text-[#0f0] animate-pulse select-none"><div className="flex flex-col items-center gap-1"><span>▲</span>diff --git a/screenpipe-app-tauri/src-tauri/Cargo.lock b/screenpipe-app-tauri/src-tauri/Cargo.lockindex 44953937d..6ba600966 100755--- a/screenpipe-app-tauri/src-tauri/Cargo.lock+++ b/screenpipe-app-tauri/src-tauri/Cargo.lock@@ -3777,7 +3777,7 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"[[package]]name = "screenpipe-app"-version = "0.8.5"+version = "0.8.6"dependencies = ["anyhow","axum",diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.tomlindex 216beac6e..e09b5113d 100644--- a/screenpipe-app-tauri/src-tauri/Cargo.toml+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "screenpipe-app"-version = "0.8.5"+version = "0.8.6"description = ""authors = ["you"]license = ""diff --git a/screenpipe-server/examples/timeline_ui_simple/index.html b/screenpipe-server/examples/timeline_ui_simple/index.htmlindex 1771a12ba..1024725cb 100644--- a/screenpipe-server/examples/timeline_ui_simple/index.html+++ b/screenpipe-server/examples/timeline_ui_simple/index.html@@ -97,6 +97,18 @@.icon:hover .tooltip {display: block;}++ .devices-container {+ display: flex;+ gap: 20px;+ border-bottom: 1px solid #333;+ padding-bottom: 20px;+ }++ .device-frame {+ flex: 1;+ min-width: 0;+ }</style></head><body>@@ -128,55 +140,72 @@document.getElementById('frames').innerHTML = '';}- function appendFrame(frame, timestamp, data) {+ function appendFrame(data) {const container = document.createElement('div');container.className = 'frame-container';- const img = document.createElement('img');- img.onerror = (e) => console.error('Failed to load image:', e);- img.onload = () => console.log('Image loaded successfully');-- const cleanBase64 = frame.trim().replace(/\s/g, '');- img.src = `data:image/jpeg;base64,${cleanBase64}`;-- img.style.display = 'block';- img.style.minHeight = '100px';-const ts = document.createElement('div');ts.className = 'frame-timestamp';- ts.innerText = new Date(timestamp).toLocaleString();-- const metadata = document.createElement('div');- metadata.className = 'metadata-icons';+ ts.innerText = new Date(data.timestamp).toLocaleString();+ container.appendChild(ts);- metadata.innerHTML = `- <span>window: ${(data && data.window_name) || 'N/A'}</span>- <span>app: ${(data && data.app_name) || 'N/A'}</span>- `;-- if (data && data.ocr_text) {- const ocrIcon = document.createElement('div');- ocrIcon.className = 'icon';- ocrIcon.innerHTML = `- 📝- <div class="tooltip">OCR: ${data.ocr_text}</div>+ const devicesContainer = document.createElement('div');+ devicesContainer.className = 'devices-container';++ data.devices.forEach(device => {+ const deviceFrame = document.createElement('div');+ deviceFrame.className = 'device-frame';++ const img = document.createElement('img');+ img.onerror = (e) => console.error('Failed to load image:', e);+ img.onload = () => console.log('Image loaded successfully');++ const cleanBase64 = device.frame.trim().replace(/\s/g, '');+ img.src = `data:image/jpeg;base64,${cleanBase64}`;++ img.style.display = 'block';+ img.style.minHeight = '100px';++ const metadata = document.createElement('div');+ metadata.className = 'metadata-icons';++ metadata.innerHTML = `+ <span>device: ${device.device_id}</span>+ <span>window: ${device.metadata.window_name || 'N/A'}</span>+ <span>app: ${device.metadata.app_name || 'N/A'}</span>`;- metadata.appendChild(ocrIcon);- }- if (data && data.transcription) {- const transcriptionIcon = document.createElement('div');- transcriptionIcon.className = 'icon';- transcriptionIcon.innerHTML = `- 🎤- <div class="tooltip">Transcription: ${data.transcription}</div>- `;- metadata.appendChild(transcriptionIcon);- }+ if (device.metadata.ocr_text) {+ const ocrIcon = document.createElement('div');+ ocrIcon.className = 'icon';+ ocrIcon.innerHTML = `+ 📝+ <div class="tooltip">OCR: ${device.metadata.ocr_text}</div>+ `;+ metadata.appendChild(ocrIcon);+ }++ device.audio.forEach(audio => {+ const audioIcon = document.createElement('div');+ audioIcon.className = 'icon';+ audioIcon.innerHTML = `+ ${audio.is_input ? '🎤' : '🔊'}+ <div class="tooltip">+ Device: ${audio.device_name}+ Duration: ${audio.duration_secs}s+ Offset: ${audio.start_offset}s+ Transcription: ${audio.transcription}+ </div>+ `;+ metadata.appendChild(audioIcon);+ });++ deviceFrame.appendChild(img);+ deviceFrame.appendChild(metadata);+ devicesContainer.appendChild(deviceFrame);+ });- container.appendChild(img);- container.appendChild(ts);- container.appendChild(metadata);+ container.appendChild(devicesContainer);const frames = document.getElementById('frames');frames.appendChild(container);@@ -203,9 +232,9 @@return;}- if (data.frame && data.timestamp) {- console.log('appending frame from:', data.timestamp, data);- appendFrame(data.frame, data.timestamp, data);+ if (data.timestamp && data.devices) {+ console.log('appending frames from:', data.timestamp, data);+ appendFrame(data);}} catch (e) {console.error('Failed to parse frame data:', e);diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex 17bd7f75a..44a2baf09 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -100,7 +100,6 @@ fn setup_logging(local_data_dir: &PathBuf, cli: &Cli) -> anyhow::Result<WorkerGu.with(fmt::layer().with_writer(non_blocking)).init();- info!("logging initialized");Ok(guard)}@@ -264,7 +263,6 @@ async fn main() -> anyhow::Result<()> {eprintln!("no audio devices available. audio recording will be disabled.");} else {for device in &audio_devices {- info!(" {}", device);let device_control = DeviceControl {is_running: true,@@ -292,10 +290,7 @@ async fn main() -> anyhow::Result<()> {e})?,);- info!(- "database initialized, will store files in {}",- local_data_dir.to_string_lossy()- );+let db_server = db.clone();// Channel for controlling the recorder ! TODO RENAME SHIT@@ -496,6 +491,9 @@ async fn main() -> anyhow::Result<()> {"│ friend wearable uid │ {:<34} │",cli.friend_wearable_uid.as_deref().unwrap_or("not set"));+ println!("│ ui monitoring │ {:<34} │", cli.enable_ui_monitoring);+ println!("│ frame cache │ {:<34} │", cli.enable_frame_cache);+const VALUE_WIDTH: usize = 34;// Function to truncate and pad strings@@ -613,8 +611,6 @@ async fn main() -> anyhow::Result<()> {}}- println!("│ ui monitoring │ {:<34} │", cli.enable_ui_monitoring);-println!("└─────────────────────┴────────────────────────────────────┘");// Add warning for cloud arguments and telemetrydiff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rsindex 2412efdf6..a7edb58ce 100644--- a/screenpipe-server/src/db.rs+++ b/screenpipe-server/src/db.rs@@ -189,7 +189,7 @@ impl DatabaseManager {return Err(e);}- info!("Migrations executed successfully.");+ debug!("migrations executed successfully.");Ok(db_manager)}@@ -1175,7 +1175,7 @@ impl DatabaseManager {JOIN video_chunks vc ON f.video_chunk_id = vc.idLEFT JOIN ocr_text ot ON f.id = ot.frame_idWHERE f.timestamp >= ?1 AND f.timestamp <= ?2- ORDER BY f.timestamp, f.offset_index+ ORDER BY f.timestamp DESC, f.offset_index DESC"#;// Then get audio data that overlaps with these frames@@ -1189,7 +1189,7 @@ impl DatabaseManager {FROM audio_transcriptions atJOIN audio_chunks ac ON at.audio_chunk_id = ac.idWHERE at.timestamp >= ?1 AND at.timestamp <= ?2- ORDER BY at.timestamp+ ORDER BY at.timestamp DESC"#;// Execute both queries@@ -1251,7 +1251,7 @@ impl DatabaseManager {}Ok(TimeSeriesChunk {- frames: frames_map.into_values().collect(),+ frames: frames_map.into_values().rev().collect(),start_time: start,end_time: end,})diff --git a/screenpipe-server/src/migrations/20241103222151_timeline_indexes.sql b/screenpipe-server/src/migrations/20241103222151_timeline_indexes.sqlnew file mode 100644index 000000000..098f89ae8--- /dev/null+++ b/screenpipe-server/src/migrations/20241103222151_timeline_indexes.sql@@ -0,0 +1,9 @@+-- Add migration script here++-- For the frames query optimization+CREATE INDEX IF NOT EXISTS idx_frames_timestamp_offset_index ON frames(timestamp, offset_index);+CREATE INDEX IF NOT EXISTS idx_ocr_text_frame_id ON ocr_text(frame_id);++-- Composite index for ocr_text that might help with the LEFT JOIN+CREATE INDEX IF NOT EXISTS idx_ocr_text_frame_app_window ON ocr_text(frame_id, app_name, window_name);+diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rsindex f5ee0a513..2d69fc4ca 100644--- a/screenpipe-server/src/video.rs+++ b/screenpipe-server/src/video.rs@@ -39,7 +39,6 @@ impl VideoCapture {include_list: &[String],languages: Vec<Language>,) -> Self {- info!("Starting new video capture");let fps = if fps.is_finite() && fps > 0.0 {fps} else {@@ -71,7 +70,6 @@ impl VideoCapture {.await;});- info!("Started capture thread");// In the _queue_threadlet _queue_thread = tokio::spawn(async move {diff --git a/screenpipe-server/src/video_cache.rs b/screenpipe-server/src/video_cache.rsindex 078cc2048..7d0a4699f 100644--- a/screenpipe-server/src/video_cache.rs+++ b/screenpipe-server/src/video_cache.rs@@ -1,29 +1,3 @@-/*--### Video Cache Rules--✅ **DO**-- index ALL files in memory (just paths + metadata, ~10MB RAM)-- cache last 5min full-res, 1h low-res (640px)-- use ffmpeg for frame extraction (JPEG, q=3/8)-- use filesystem metadata for timestamps-- handle timeouts (30s max)-- refresh index every 30s--❌ **DON'T**-- parse filenames for dates-- cache full video files in RAM-- keep file handles open-- use more than 1GB RAM total-- block on frame extraction / slowness-- process files modified in last 60s--We should be able to allow users to:-- stream frames at high speed from current timestamp, 10 min around-- go back in time fast, like 2 months ago---*/use anyhow::Result;use bincode;use chrono::{DateTime, Duration, Utc};@@ -33,20 +7,18 @@ use serde::{Deserialize, Serialize};use sha2::{Digest, Sha256};use std::collections::{BTreeMap, HashMap};use std::path::PathBuf;-use std::sync::atomic::AtomicBool;use std::sync::Arc;use std::time::SystemTime;use tokio::fs;-use tokio::io::AsyncBufReadExt;use tokio::process::Command;-use tokio::sync::mpsc::{channel, Sender};-use tokio::sync::RwLock;+use tokio::sync::mpsc::Sender;+use tokio::sync::{mpsc, oneshot};use tracing::{debug, error};use crate::db::{FrameData, OCREntry};use crate::DatabaseManager;-type FrameChannel = Sender<TimeSeriesFrame>;+type FrameChannel = mpsc::Sender<TimeSeriesFrame>;#[derive(Debug, Clone)]pub struct TimeSeriesFrame {@@ -80,10 +52,20 @@ pub struct FrameMetadata {pub ocr_text: String,}-pub struct FrameInfo {- pub timestamp: DateTime<Utc>,- pub data: Vec<u8>,- pub metadata: FrameMetadata,+#[derive(Debug)]+enum CacheMessage {+ Store {+ cache_key: String,+ frame_data: Vec<u8>,+ device_data: OCREntry,+ audio_entries: Vec<AudioEntry>,+ response: oneshot::Sender<Result<()>>,+ },+ Get {+ cache_key: String,+ response:+ oneshot::Sender<Result<Option<(Vec<u8>, FrameMetadata, (DateTime<Utc>, String))>>>,+ },}#[derive(Debug, Serialize, Deserialize)]@@ -107,7 +89,7 @@ enum CompressionType {}#[derive(Debug)]-pub struct CacheEntry {+struct CacheEntry {frame: CachedFrame,path: PathBuf,last_accessed: SystemTime,@@ -132,7 +114,7 @@ impl Default for CacheConfig {}}-pub struct FrameDiskCache {+struct FrameDiskCache {config: CacheConfig,entries: BTreeMap<(DateTime<Utc>, String), CacheEntry>,total_size: u64,@@ -144,10 +126,8 @@ impl FrameDiskCache {let cache_dir = &config.cache_dir;let index_path = cache_dir.join("cache_index.bin");- // Ensure cache directory existsfs::create_dir_all(cache_dir).await?;- // Initialize empty cachelet mut cache = Self {config,entries: BTreeMap::new(),@@ -155,16 +135,13 @@ impl FrameDiskCache {index_path,};- // Try to load existing index, but don't fail if it doesn't existif cache.index_path.exists() {if let Err(e) = cache.load_index().await {debug!("could not load existing cache index: {}", e);- // Clear any partial datacache.entries.clear();cache.total_size = 0;}} else {- // Create empty index filecache.save_index().await?;}@@ -191,16 +168,10 @@ impl FrameDiskCache {}debug!("loaded {} cached frames", self.entries.len());}- Err(e) => {- error!("failed to deserialize cache index: {}", e);- }+ Err(e) => error!("failed to deserialize cache index: {}", e),},- Ok(_) => {- debug!("cache index is empty, starting fresh");- }- Err(e) => {- error!("failed to read cache index: {}", e);- }+ Ok(_) => debug!("cache index is empty, starting fresh"),+ Err(e) => error!("failed to read cache index: {}", e),}Ok(())}@@ -208,28 +179,18 @@ impl FrameDiskCache {async fn save_index(&self) -> Result<()> {let frames: Vec<_> = self.entries.values().map(|entry| &entry.frame).collect();let temp_path = self.index_path.with_extension("tmp");-- // Initialize with empty Vec if no frameslet encoded = if frames.is_empty() {bincode::serialize(&Vec::<CachedFrame>::new())?} else {bincode::serialize(&frames)?};- // Write to temporary file- fs::write(&temp_path, encoded)- .await- .map_err(|e| anyhow::anyhow!("failed to write temp index: {}", e))?;-- // Atomically rename- fs::rename(&temp_path, &self.index_path)- .await- .map_err(|e| anyhow::anyhow!("failed to rename temp index: {}", e))?;-+ fs::write(&temp_path, encoded).await?;+ fs::rename(&temp_path, &self.index_path).await?;Ok(())}- pub async fn store_frame(+ async fn store_frame(&mut self,cache_key: &str,frame_data: &[u8],@@ -241,7 +202,6 @@ impl FrameDiskCache {.split_once("||").ok_or_else(|| anyhow::anyhow!("invalid cache key format"))?;- // Clean up the timestamp stringlet clean_timestamp = timestamp_str.trim_end_matches(" UTC").replace(' ', "T")@@ -260,31 +220,28 @@ impl FrameDiskCache {let frame_path = self.get_frame_path(×tamp.into(), device_id);- // Ensure parent directory existsif let Some(parent) = frame_path.parent() {fs::create_dir_all(parent).await?;}- // Calculate checksumlet mut hasher = Sha256::new();hasher.update(frame_data);let checksum = format!("{:x}", hasher.finalize());- // Create cached frame entrylet cached_frame = CachedFrame {timestamp: timestamp.into(),device_id: device_id.to_string(),checksum,metadata: FrameMetadata {file_path: device_data.video_file_path.clone(),- app_name: device_data.app_name,- window_name: device_data.window_name,+ app_name: device_data.app_name.clone(),+ window_name: device_data.window_name.clone(),transcription: audio_entries.iter().map(|a| a.transcription.clone()).collect::<Vec<_>>().join(" "),- ocr_text: device_data.text,+ ocr_text: device_data.text.clone(),},frame_size: frame_data.len() as u64,compression: CompressionType::Jpeg {@@ -295,12 +252,8 @@ impl FrameDiskCache {audio_entries: audio_entries.to_vec(),};- // Write frame data- fs::write(&frame_path, frame_data)- .await- .map_err(|e| anyhow::anyhow!("failed to write frame data: {}", e))?;+ fs::write(&frame_path, frame_data).await?;- // Update in-memory entriesself.entries.insert((timestamp.into(), device_id.to_string()),CacheEntry {@@ -316,7 +269,7 @@ impl FrameDiskCache {Ok(())}- pub async fn get_frame_data(+ async fn get_frame_data(&self,cache_key: &str,) -> Result<Option<(Vec<u8>, FrameMetadata, (DateTime<Utc>, String))>> {@@ -338,7 +291,6 @@ impl FrameDiskCache {let frame_data = fs::read(&frame_path).await?;- // Find the entry in our in-memory cacheif let Some(entry) = self.entries.get(&(timestamp.into(), device_id.to_string())) {let mut hasher = Sha256::new();hasher.update(&frame_data);@@ -368,10 +320,36 @@ impl FrameDiskCache {}}+async fn run_cache_manager(mut cache: FrameDiskCache, mut rx: mpsc::Receiver<CacheMessage>) {+ while let Some(msg) = rx.recv().await {+ match msg {+ CacheMessage::Store {+ cache_key,+ frame_data,+ device_data,+ audio_entries,+ response,+ } => {+ let result = cache+ .store_frame(&cache_key, &frame_data, device_data, &audio_entries)+ .await;+ let _ = response.send(result);+ }+ CacheMessage::Get {+ cache_key,+ response,+ } => {+ let result = cache.get_frame_data(&cache_key).await;+ let _ = response.send(result);+ }+ }+ }+}+#[derive(Clone)]pub struct FrameCache {pub screenpipe_dir: PathBuf,- pub disk_cache: Arc<RwLock<FrameDiskCache>>,+ cache_tx: mpsc::Sender<CacheMessage>,db: Arc<DatabaseManager>,}@@ -384,15 +362,16 @@ impl FrameCache {fs::create_dir_all(&cache_config.cache_dir).await?;- let disk_cache = Arc::new(RwLock::new(FrameDiskCache::new(cache_config).await?));+ let (cache_tx, cache_rx) = mpsc::channel(100);+ let disk_cache = FrameDiskCache::new(cache_config).await?;- let cache = Self {- screenpipe_dir: screenpipe_dir.clone(),- disk_cache,- db,- };+ tokio::spawn(run_cache_manager(disk_cache, cache_rx));- Ok(cache)+ Ok(Self {+ screenpipe_dir,+ cache_tx,+ db,+ })}async fn extract_frames_batch(@@ -408,9 +387,11 @@ impl FrameCache {start_time, end_time);- // First, get all the video chunks and organize by timestamp- let chunks = self.db.find_video_chunks(start_time, end_time).await?;-+ let mut chunks = self.db.find_video_chunks(start_time, end_time).await?;++ // Sort frames in descending order by timestamp+ chunks.frames.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));+debug!("found {} chunks", chunks.frames.len());let frame_times = chunks@@ -426,25 +407,24 @@ impl FrameCache {frame_times.len());- // Process each timestampfor chunk in &chunks.frames {let mut timeseries_frame = TimeSeriesFrame {timestamp: chunk.timestamp,frame_data: Vec::new(),};- // Check cache first for each device - acquire lock only when neededfor device_data in &chunk.ocr_entries {- let cache_key = format!("{}:{}", chunk.timestamp, device_data.device_name);-- // Acquire read lock only for cache lookup- if let Some((frame_data, metadata, _)) = self- .disk_cache- .read()- .await- .get_frame_data(&cache_key)- .await?- {+ let cache_key = format!("{}||{}", chunk.timestamp, device_data.device_name);++ let (response_tx, response_rx) = oneshot::channel();+ self.cache_tx+ .send(CacheMessage::Get {+ cache_key: cache_key.clone(),+ response: response_tx,+ })+ .await?;++ if let Ok(Some((frame_data, metadata, _))) = response_rx.await? {timeseries_frame.frame_data.push(DeviceFrame {device_id: device_data.device_name.clone(),image_data: frame_data,@@ -462,7 +442,6 @@ impl FrameCache {.collect(),});} else {- // Cache miss - queue for extractionextraction_queue.entry(device_data.video_file_path.clone()).or_insert_with(Vec::new)@@ -470,23 +449,20 @@ impl FrameCache {}}- // If we have any frames for this timestamp, send themif !timeseries_frame.frame_data.is_empty() {frame_tx.send(timeseries_frame).await?;}}- // Process extraction queuelet ffmpeg = find_ffmpeg_path().ok_or_else(|| anyhow::anyhow!("ffmpeg not found"))?;- // Process each taskfor (file_path, tasks) in extraction_queue {extract_frame(ffmpeg.clone(),file_path,tasks,frame_tx.clone(),- self.disk_cache.clone(),+ self.cache_tx.clone(),).await?;}@@ -505,49 +481,62 @@ impl FrameCache {let start = timestamp - Duration::minutes(duration_minutes / 2);let end = timestamp + Duration::minutes(duration_minutes / 2);- let (extract_tx, mut extract_rx) = channel(100);- let done = Arc::new(AtomicBool::new(false));- let done_clone = done.clone();-- let cache_clone = self.clone();- let mut extract_handle = tokio::spawn(async move {- debug!("starting frame extraction");- let result = cache_clone- .extract_frames_batch(start, end, extract_tx.clone())- .await;- // Explicitly drop the sender after extraction is done to finish the channel- drop(extract_tx);- done_clone.store(true, std::sync::atomic::Ordering::Release);- debug!("frame extraction completed");- result- });-- // Create a select future that completes when either:- // 1. We receive a frame from extract_rx- // 2. The extract_handle completes- loop {- if done.load(std::sync::atomic::Ordering::Acquire) {- break;- }+ let (extract_tx, mut extract_rx) = mpsc::channel(100);++ let mut extraction_handle = {+ let cache_clone = self.clone();+ tokio::spawn(async move {+ let result = cache_clone+ .extract_frames_batch(start, end, extract_tx)+ .await;+ debug!("extraction task finished with result: {:?}", result.is_ok());+ result+ })+ };- tokio::select! {- frame = extract_rx.recv() => {- match frame {- Some(timeseries_frame) => {- debug!("sending frame at {} to client", timeseries_frame.timestamp);- frame_tx.send(timeseries_frame).await?;+ // 30 s x duration of the requested time range+ let timeout_duration = tokio::time::Duration::from_secs(10 * duration_minutes as u64);+ let result = tokio::time::timeout(timeout_duration, async {+ loop {+ tokio::select! {+ maybe_frame = extract_rx.recv() => {+ match maybe_frame {+ Some(frame) => {+ if let Err(e) = frame_tx.send(frame).await {+ debug!("client channel closed, stopping: {}", e);+ break;+ }+ }+ None => {+ debug!("extraction channel closed, stopping");+ break;+ }}- None => break, // Channel closed, extraction complete}- }- result = &mut extract_handle => {- result??; // Propagate any errors- break;+ result = &mut extraction_handle => {+ match result {+ Ok(Ok(())) => debug!("extraction task completed successfully"),+ Ok(Err(e)) => debug!("extraction task failed: {}", e),+ Err(e) => debug!("extraction task panicked: {}", e),+ }+ break;+ }}}- }+ })+ .await;- Ok(())+ match result {+ Ok(_) => Ok(()),+ Err(_) => {+ debug!(+ "frame extraction timed out after {} seconds",+ timeout_duration.as_secs()+ );+ // Err(anyhow::anyhow!("frame extraction timed out"))+ Ok(())+ }+ }}}@@ -556,14 +545,13 @@ async fn extract_frame(video_file_path: String,tasks: Vec<(FrameData, OCREntry)>,frame_tx: FrameChannel,- disk_cache: Arc<RwLock<FrameDiskCache>>,+ cache_tx: mpsc::Sender<CacheMessage>,) -> Result<()> {if !is_video_file_complete(&ffmpeg, &video_file_path).await? {debug!("skipping incomplete video file: {}", video_file_path);return Ok(());}- // Extract ALL frames as separate JPEGslet temp_dir = tempfile::tempdir()?;let output_pattern = temp_dir.path().join("frame%d.jpg");@@ -588,7 +576,6 @@ async fn extract_frame(return Ok(());}- // Read all frameslet mut entries = tokio::fs::read_dir(temp_dir.path()).await?;while let Some(entry) = entries.next_entry().await? {let frame_data = tokio::fs::read(entry.path()).await?;@@ -599,39 +586,35 @@ async fn extract_frame(video_file_path);- // Group frames by timestamplet mut frames_by_timestamp: HashMap<DateTime<Utc>, Vec<DeviceFrame>> = HashMap::new();- // Process all tasks for this video filefor (chunk, device_data) in &tasks {let cache_key = format!("{}||{}", chunk.timestamp, device_data.device_name);- // Cache the frame- {- let mut cache = disk_cache.write().await;- cache- .store_frame(- &cache_key,- &frame_data,- device_data.clone(),- &chunk- .audio_entries- .iter()- .map(|a| AudioEntry {- transcription: a.transcription.clone(),- device_name: a.device_name.clone(),- is_input: a.is_input,- audio_file_path: a.audio_file_path.clone(),- duration_secs: a.duration_secs,- })- .collect::<Vec<_>>(),- )- .await?;- drop(cache);- }+ let (response_tx, response_rx) = oneshot::channel();+ cache_tx+ .send(CacheMessage::Store {+ cache_key: cache_key.clone(),+ frame_data: frame_data.clone(),+ device_data: device_data.clone(),+ audio_entries: chunk+ .audio_entries+ .iter()+ .map(|a| AudioEntry {+ transcription: a.transcription.clone(),+ device_name: a.device_name.clone(),+ is_input: a.is_input,+ audio_file_path: a.audio_file_path.clone(),+ duration_secs: a.duration_secs,+ })+ .collect(),+ response: response_tx,+ })+ .await?;++ response_rx.await??;debug!("cached frame for {}", device_data.device_name);- // Group frames by timestampframes_by_timestamp.entry(chunk.timestamp).or_default()@@ -664,7 +647,6 @@ async fn extract_frame(});}- // Send all frames for each timestampfor (timestamp, device_frames) in frames_by_timestamp {frame_tx.send(TimeSeriesFrame {diff --git a/screenpipe-server/tests/video_cache_test.rs b/screenpipe-server/tests/video_cache_test.rsindex 54d599a84..fa53d1b4c 100644--- a/screenpipe-server/tests/video_cache_test.rs+++ b/screenpipe-server/tests/video_cache_test.rs@@ -365,222 +365,76 @@ async fn test_basic_frame_retrieval() -> Result<()> {}#[tokio::test]-async fn test_frame_storage() -> Result<()> {+async fn test_frame_ordering() -> Result<()> {let (cache, _db) = setup_test_env().await?;- // Create test frame data- let test_timestamp = Utc::now();- let test_device_id = "test_device";- let cache_key = format!("{}||{}", test_timestamp.to_rfc3339(), test_device_id);-- // Create sample JPEG data (minimal valid JPEG)- let frame_data = vec![- 0xFF, 0xD8, // SOI marker- 0xFF, 0xE0, 0x00, 0x10, // APP0 segment- 0x4A, 0x46, 0x49, 0x46, // "JFIF"- 0x00, 0x01, 0x01, 0x00, // version, units- 0x00, 0x01, 0x00, 0x01, // density- 0x00, 0x00, // thumbnail- 0xFF, 0xD9, // EOI marker- ];-- // Create test OCR entry- let ocr_entry = OCREntry {- device_name: test_device_id.to_string(),- video_file_path: "test_video.mp4".to_string(),- app_name: "test_app".to_string(),- window_name: "test_window".to_string(),- text: "test ocr text".to_string(),- };-- // Create test audio entries- let audio_entries = vec![AudioEntry {- transcription: "test transcription".to_string(),- device_name: test_device_id.to_string(),- is_input: true,- audio_file_path: "test_audio.wav".to_string(),- duration_secs: 1.0,- }];-- // Get write access to disk cache- let mut disk_cache = cache.disk_cache.write().await;-- debug!("storing frame");- // Store the frame- disk_cache- .store_frame(&cache_key, &frame_data, ocr_entry, &audio_entries)- .await?;-- debug!("saved frame");-- // Drop write lock- drop(disk_cache);-- // Get read access to verify storage- let disk_cache = cache.disk_cache.read().await;-- // Verify frame was stored correctly- if let Some((stored_data, metadata, (stored_timestamp, stored_device))) =- disk_cache.get_frame_data(&cache_key).await?- {- // Verify frame data- assert_eq!(stored_data, frame_data, "Frame data mismatch");-- // Verify metadata- assert_eq!(metadata.app_name, "test_app", "App name mismatch");- assert_eq!(metadata.window_name, "test_window", "Window name mismatch");- assert_eq!(metadata.ocr_text, "test ocr text", "OCR text mismatch");-- // Verify timestamp and device- assert_eq!(stored_timestamp, test_timestamp, "Timestamp mismatch");- assert_eq!(stored_device, test_device_id, "Device ID mismatch");-- println!("✅ frame storage test passed:");- println!("- stored {} bytes of frame data", stored_data.len());- println!("- metadata verified");- println!("- timestamp and device ID verified");- } else {- panic!("Failed to retrieve stored frame");- }-- Ok(())-}--#[tokio::test]-async fn test_frame_storage_edge_cases() -> Result<()> {- let (cache, _db) = setup_test_env().await?;-- // Test cases with potentially problematic timestamps and device IDs- let test_cases = vec![- // Regular case (control)- (Utc::now(), "monitor_1", "normal case"),- // Timestamp edge cases- (Utc::now(), "monitor||1", "device id with pipes"),- (Utc::now(), "monitor 1", "device id with spaces"),- (Utc::now(), "monitor/1", "device id with slash"),- (Utc::now(), "monitor\\1", "device id with backslash"),- // Special characters- (Utc::now(), "monitor#1", "device id with hash"),- (Utc::now(), "monitor:1", "device id with colon"),- (Utc::now(), "monitor?1", "device id with question mark"),- ];-- // Sample frame data (minimal valid JPEG)- let frame_data = vec![- 0xFF, 0xD8, // SOI marker- 0xFF, 0xE0, 0x00, 0x10, // APP0 segment- 0x4A, 0x46, 0x49, 0x46, // "JFIF"- 0x00, 0x01, 0x01, 0x00, // version, units- 0x00, 0x01, 0x00, 0x01, // density- 0x00, 0x00, // thumbnail- 0xFF, 0xD9, // EOI marker- ];-- println!("\nTesting frame storage edge cases:");- println!("--------------------------------");+ // Get frames from last 10 minutes to ensure we have enough samples+ let target_time = Utc::now() - Duration::minutes(5);+ let (tx, mut rx) = tokio::sync::mpsc::channel(100);- for (timestamp, device_id, test_desc) in test_cases {- println!("\nTesting: {}", test_desc);- println!("Timestamp: {}", timestamp);- println!("Device ID: {}", device_id);+ println!("\nframe ordering test:");+ println!("------------------");+ println!("target time: {}", target_time);- let cache_key = format!("{}||{}", timestamp.to_rfc3339(), device_id);- println!("Cache key: {}", cache_key);+ // Request frames with a 10-minute window+ cache.get_frames(target_time, 10, tx, true).await?;- // Create test OCR entry- let ocr_entry = OCREntry {- device_name: device_id.to_string(),- video_file_path: "test_video.mp4".to_string(),- app_name: "test_app".to_string(),- window_name: "test_window".to_string(),- text: "test ocr text".to_string(),- };+ let mut frames = Vec::new();+ let timeout = tokio::time::sleep(std::time::Duration::from_secs(30));+ tokio::pin!(timeout);- // Create test audio entries- let audio_entries = vec![AudioEntry {- transcription: "test transcription".to_string(),- device_name: device_id.to_string(),- is_input: true,- audio_file_path: "test_audio.wav".to_string(),- duration_secs: 1.0,- }];-- // Get write access to disk cache- let mut disk_cache = cache.disk_cache.write().await;-- // Try to store the frame and capture the result- match disk_cache- .store_frame(&cache_key, &frame_data, ocr_entry, &audio_entries)- .await- {- Ok(_) => {- println!("✅ Successfully stored frame");- // Try retrieve only if storage succeeded- match disk_cache.get_frame_data(&cache_key).await {- Ok(Some(_)) => println!("✅ Successfully retrieved frame"),- Ok(None) => println!("❌ Frame not found after storage"),- Err(e) => println!("❌ Error retrieving frame: {}", e),+ // Collect all frames+ loop {+ tokio::select! {+ frame = rx.recv() => {+ match frame {+ Some(f) => {+ frames.push(f);+ }+ None => break,}}- Err(e) => println!("❌ Failed to store frame: {}", e),+ _ = &mut timeout => {+ println!("timeout waiting for frames!");+ break;+ }}}- Ok(())-}+ println!("received {} frames", frames.len());-#[tokio::test]-async fn test_frame_storage_with_rfc3339_variations() -> Result<()> {- let (cache, _db) = setup_test_env().await?;-- // Test cases with different RFC3339 timestamp formats- let test_cases = vec![- // Standard format- "2024-11-03T01:05:11.690182Z",- // With space instead of T- "2024-11-03 01:05:11.690182Z",- // Without microseconds- "2024-11-03T01:05:11Z",- // With offset- "2024-11-03T01:05:11+00:00",- ];+ // Verify ordering+ let mut is_ordered = true;+ let mut prev_timestamp = None;- let frame_data = vec![0xFF, 0xD8, 0xFF, 0xD9]; // Minimal JPEG- let device_id = "monitor_1";-- println!("\nTesting RFC3339 timestamp variations:");- println!("-----------------------------------");-- for timestamp_str in test_cases {- println!("\nTesting timestamp: {}", timestamp_str);+ for (i, frame) in frames.iter().enumerate() {+ if let Some(prev) = prev_timestamp {+ if frame.timestamp > prev {+ is_ordered = false;+ println!(+ "❌ ordering violation at index {}: {} > {} (should be descending)",+ i, frame.timestamp, prev+ );+ }+ }+ prev_timestamp = Some(frame.timestamp);+ }- let cache_key = format!("{}||{}", timestamp_str, device_id);- println!("Cache key: {}", cache_key);+ assert!(+ is_ordered,+ "frames should be in descending order (newest first)"+ );- let ocr_entry = OCREntry {- device_name: device_id.to_string(),- video_file_path: "test_video.mp4".to_string(),- app_name: "test_app".to_string(),- window_name: "test_window".to_string(),- text: "test ocr text".to_string(),- };+ // Print first few and last few timestamps to visualize the ordering+ println!("\nfirst 3 frames (should be newest):");+ for frame in frames.iter().take(3) {+ println!(" {}", frame.timestamp);+ }- let audio_entries = vec![AudioEntry {- transcription: "test transcription".to_string(),- device_name: device_id.to_string(),- is_input: true,- audio_file_path: "test_audio.wav".to_string(),- duration_secs: 1.0,- }];-- let mut disk_cache = cache.disk_cache.write().await;-- match disk_cache- .store_frame(&cache_key, &frame_data, ocr_entry, &audio_entries)- .await- {- Ok(_) => println!("✅ Successfully stored frame"),- Err(e) => println!("❌ Failed to store frame: {}", e),+ if frames.len() > 3 {+ println!("\nlast 3 frames (should be oldest):");+ for frame in frames.iter().rev().take(3) {+ println!(" {}", frame.timestamp);}}