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

(rewind pipe)add proper scroll (#1203)

shaik-zeeshan2bf527060144
diff --git a/pipes/rewind/bun.lockb b/pipes/rewind/bun.lockb
index c2eca629a..bef0b4590 100755
Binary files a/pipes/rewind/bun.lockb and b/pipes/rewind/bun.lockb differ
diff --git a/pipes/rewind/package.json b/pipes/rewind/package.json
index d9ab60e48..8d004ee59 100644
--- a/pipes/rewind/package.json
+++ b/pipes/rewind/package.json
@@ -53,7 +53,8 @@
"remark-gfm": "^4.0.0",
"remark-math": "^6.0.0",
"tailwind-merge": "^2.5.5",
- "tailwindcss-animate": "^1.0.7"
+ "tailwindcss-animate": "^1.0.7",
+ "zustand": "^5.0.3"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
@@ -61,6 +62,7 @@
"@types/react": "^19",
"@types/react-dom": "^19",
"autoprefixer": "^10.4.20",
+ "eslint": "^9.19.0",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.16",
"typescript": "^5"
diff --git a/pipes/rewind/src/app/globals.css b/pipes/rewind/src/app/globals.css
index ff005b73a..be20610d0 100644
--- a/pipes/rewind/src/app/globals.css
+++ b/pipes/rewind/src/app/globals.css
@@ -69,4 +69,12 @@ body {
body {
@apply bg-background text-foreground !pointer-events-auto;
}
+ .scrollbar-hide {
+ -ms-overflow-style: none; /* IE and Edge */
+ scrollbar-width: none; /* Firefox */
+ }
+
+ .scrollbar-hide::-webkit-scrollbar {
+ display: none; /* Chrome, Safari and Opera */
+ }
}
diff --git a/pipes/rewind/src/app/page.tsx b/pipes/rewind/src/app/page.tsx
index 710e06f4b..0984e8f8e 100644
--- a/pipes/rewind/src/app/page.tsx
+++ b/pipes/rewind/src/app/page.tsx
@@ -1,5 +1,5 @@
"use client";
-import { useEffect, useState, useRef, useMemo } from "react";
+import { useEffect, useState, useRef, useMemo, useCallback } from "react";
import { Loader2, RotateCcw, AlertCircle } from "lucide-react";
import { TimelineIconsSection } from "@/components/timeline/timeline-dock-section";
import { AudioTranscript } from "@/components/timeline/audio-transcript";
@@ -11,632 +11,471 @@ import { TimelineSelection } from "@/components/timeline/timeline-selection";
import { TimelineControls } from "@/components/timeline/timeline-controls";
import { TimelineSearch } from "@/components/timeline/timeline-search";
import { TimelineSearch2 } from "@/components/timeline/timeline-search-v2";
+import { isAfter, isSameDay } from "date-fns";
+import { getStartDate } from "@/lib/actions/get-start-date";
+import { useTimelineData } from "@/lib/hooks/use-timeline-data";
+import { useCurrentFrame } from "@/lib/hooks/use-current-frame";
+import { TimelineSlider } from "@/components/timeline/timeline";
+import { useTimelineStore } from "@/lib/hooks/use-timeline-store";
export interface StreamTimeSeriesResponse {
- timestamp: string;
- devices: DeviceFrameResponse[];
+ timestamp: string;
+ devices: DeviceFrameResponse[];
}
-interface DeviceFrameResponse {
- device_id: string;
- frame: string; // base64 encoded image
- metadata: DeviceMetadata;
- audio: AudioData[];
+export interface DeviceFrameResponse {
+ device_id: string;
+ frame_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;
- timestamp: string;
+export interface DeviceMetadata {
+ file_path: string;
+ app_name: string;
+ window_name: string;
+ ocr_text: string;
+ timestamp: string;
}
export interface AudioData {
- device_name: string;
- is_input: boolean;
- transcription: string;
- audio_file_path: string;
- duration_secs: number;
- start_offset: number;
+ device_name: string;
+ is_input: boolean;
+ transcription: string;
+ audio_file_path: string;
+ duration_secs: number;
+ start_offset: number;
}
-interface TimeRange {
- start: Date;
- end: Date;
+export interface TimeRange {
+ start: Date;
+ end: Date;
+}
+
+function getTimeArray(
+ timeObj: TimeRange | null | undefined,
+ count: number = 7,
+): string[] {
+ if (!timeObj) return [];
+ const start = new Date(timeObj.start);
+ const end = new Date(timeObj.end);
+ const totalDuration = end.getTime() - start.getTime();
+ const interval = totalDuration / (count - 1);
+
+ return Array.from({ length: count }, (_, i) => {
+ const timestamp = new Date(start.getTime() + i * interval);
+ return timestamp.toISOString();
+ });
}
// Add this easing function at the top level
const easeOutCubic = (x: number): number => {
- return 1 - Math.pow(1 - x, 3);
+ return 1 - Math.pow(1 - x, 3);
};
export default function Timeline() {
- const [currentFrame, setCurrentFrame] = useState<DeviceFrameResponse | null>(
- null
- );
- const [frames, setFrames] = useState<StreamTimeSeriesResponse[]>([]);
- const [currentIndex, setCurrentIndex] = useState(0);
- const [isLoading, setIsLoading] = useState(true);
- const [message, setMessage] = useState<string | null>(null);
- const [error, setError] = useState<string | null>(null);
- const eventSourceRef = useRef<EventSource | null>(null);
- const retryTimeoutRef = useRef<NodeJS.Timeout | null>(null);
- const [loadedTimeRange, setLoadedTimeRange] = useState<TimeRange | null>(
- null
- );
- const [isAiPanelExpanded, setIsAiPanelExpanded] = useState(false);
- const containerRef = useRef<HTMLDivElement | null>(null);
- const [aiPanelPosition, setAiPanelPosition] = useState({
- x: 0,
- y: 0,
- });
- const [currentDate, setCurrentDate] = useState(new Date());
- const [searchResults, setSearchResults] = useState<number[]>([]);
-
- useEffect(() => {
- setAiPanelPosition({
- x: window.innerWidth - 400,
- y: window.innerHeight / 4,
- });
- }, []);
-
- const setupEventSource = () => {
- if (eventSourceRef.current) {
- eventSourceRef.current.close();
- }
-
- const endTime = new Date();
- endTime.setMinutes(endTime.getMinutes() - 2);
-
- const startTime = new Date(endTime);
- startTime.setDate(startTime.getDate() - 7);
-
- const url = `http://localhost:3030/stream/frames?start_time=${startTime.toISOString()}&end_time=${endTime.toISOString()}&order=descending`;
-
- setLoadedTimeRange({
- start: startTime,
- end: endTime,
- });
-
- console.log("starting stream:", url);
- setMessage("connecting to the server...");
-
- const eventSource = new EventSource(url);
- eventSourceRef.current = eventSource;
-
- const connectionTimeout = setTimeout(() => {
- if (eventSource.readyState !== EventSource.OPEN) {
- console.error(
- "Connection timeout: Unable to establish connection, make sure screenpipe is running"
- );
- setIsLoading(false);
- setMessage(null);
- setError("unable to establish connection, is screenpipe running?");
- eventSource.close();
- }
- }, 5000);
-
- eventSource.onmessage = (event) => {
- try {
- const data = JSON.parse(event.data);
- if (data === "keep-alive-text") {
- setError((prev) => (prev !== null ? null : prev));
- setIsLoading((prev) => (prev !== false ? false : prev));
- setMessage((prev) =>
- prev !== "please wait..." ? "please wait..." : prev
- );
- return;
- }
-
- if (data.timestamp && data.devices) {
- setFrames((prev) => {
- const exists = prev.some((f) => f.timestamp === data.timestamp);
- if (exists) return prev;
-
- if (prev.length === 0) {
- const frameTime = new Date(data.timestamp);
- setLoadedTimeRange((current) => {
- if (!current) return null;
- return {
- ...current,
- start: frameTime,
- end: current.end,
- };
- });
- return [data];
- }
-
- // Find the correct insertion index using binary search
- const timestamp = new Date(data.timestamp).getTime();
- let left = 0;
- let right = prev.length;
-
- while (left < right) {
- const mid = Math.floor((left + right) / 2);
- const midTimestamp = new Date(prev[mid].timestamp).getTime();
-
- if (midTimestamp < timestamp) {
- right = mid;
- } else {
- left = mid + 1;
- }
- }
-
- const newFrames = [...prev];
- newFrames.splice(left, 0, data);
- return newFrames;
- });
-
- setCurrentFrame((prev) => prev || data.devices[0]);
- setIsLoading(false);
- setError(null);
- setMessage(null);
- }
- } catch (error) {
- console.error("failed to parse frame data:", error);
- }
- };
-
- eventSource.onerror = (error) => {
- clearTimeout(connectionTimeout);
- if (eventSource.readyState === EventSource.CLOSED) {
- console.log("stream ended (expected behavior)", error);
- setMessage(null);
- setIsLoading(false);
- return;
- }
-
- console.error("eventsource error:", error);
- };
-
- eventSource.onopen = () => {
- console.log("eventsource connection opened");
- clearTimeout(connectionTimeout);
- setError(null);
- setMessage(null);
- setIsLoading(true);
- };
- };
-
- useEffect(() => {
- setupEventSource();
- const currentRetryTimeout = retryTimeoutRef.current;
-
- return () => {
- if (eventSourceRef.current) {
- eventSourceRef.current.close();
- }
- if (currentRetryTimeout) {
- clearTimeout(currentRetryTimeout);
- }
- setIsLoading(false);
- setError(null);
- setMessage(null);
- };
- }, []);
-
- const handleScroll = useMemo(
- () =>
- throttle((e: WheelEvent) => {
- // Move these checks outside the throttle to improve performance
- const isWithinAiPanel =
- e.target instanceof Node &&
- document.querySelector(".ai-panel")?.contains(e.target);
- const isWithinAudioPanel =
- e.target instanceof Node &&
- document.querySelector(".audio-transcript-panel")?.contains(e.target);
- const isWithinTimelineDialog =
- e.target instanceof Node &&
- document.querySelector('[role="dialog"]')?.contains(e.target);
-
- if (isWithinAiPanel || isWithinAudioPanel || isWithinTimelineDialog) {
- return;
- }
-
- e.preventDefault();
- e.stopPropagation();
-
- const scrollSensitivity = 1;
- const delta = -Math.sign(e.deltaY) / scrollSensitivity;
-
- setCurrentIndex((prevIndex) => {
- const newIndex = Math.min(
- Math.max(
- 0,
- prevIndex + (delta > 0 ? Math.ceil(delta) : Math.floor(delta))
- ),
- frames.length - 1
- );
-
- if (newIndex !== prevIndex && frames[newIndex]) {
- setCurrentFrame(frames[newIndex].devices[0]);
- }
-
- return newIndex;
- });
- }, 16),
- [frames] // Only depend on frames length changes
- );
-
- const timePercentage = useMemo(() => {
- if (!frames.length || currentIndex >= frames.length || !loadedTimeRange) {
- return 0;
- }
-
- const currentFrame = frames[currentIndex];
- if (!currentFrame?.timestamp) {
- return 0;
- }
-
- const frameTime = new Date(currentFrame.timestamp);
- const totalVisibleMilliseconds =
- loadedTimeRange.end.getTime() - loadedTimeRange.start.getTime();
- const currentMilliseconds =
- frameTime.getTime() - loadedTimeRange.start.getTime();
-
- return (currentMilliseconds / totalVisibleMilliseconds) * 100;
- }, [currentIndex, frames, loadedTimeRange]);
-
- useEffect(() => {
- const preventScroll = (e: WheelEvent) => {
- const isWithinAiPanel = document
- .querySelector(".ai-panel")
- ?.contains(e.target as Node);
- const isWithinAudioPanel = document
- .querySelector(".audio-transcript-panel")
- ?.contains(e.target as Node);
- const isWithinTimelineDialog = document
- .querySelector('[role="dialog"]')
- ?.contains(e.target as Node);
-
- if (!isWithinAiPanel && !isWithinAudioPanel && !isWithinTimelineDialog) {
- e.preventDefault();
- }
- };
-
- document.addEventListener("wheel", preventScroll, { passive: false });
- return () => document.removeEventListener("wheel", preventScroll);
- }, []);
-
- const handleRefresh = () => {
- window.location.reload();
- };
-
- useEffect(() => {
- const container = containerRef.current;
- if (container) {
- container.addEventListener("wheel", handleScroll, { passive: false });
- }
-
- return () => {
- if (container) {
- container.removeEventListener("wheel", handleScroll);
- }
- };
- }, [handleScroll]);
-
- const jumpToDate = (targetDate: Date) => {
- // Find the closest frame to the target date
- if (frames.length === 0) return;
-
- const targetTime = targetDate.getTime();
- let closestIndex = 0;
- let closestDiff = Infinity;
-
- frames.forEach((frame, index) => {
- const frameTime = new Date(frame.timestamp).getTime();
- const diff = Math.abs(frameTime - targetTime);
- if (diff < closestDiff) {
- closestDiff = diff;
- closestIndex = index;
- }
- });
-
- // Update cursor position
- setCurrentIndex(closestIndex);
- if (frames[closestIndex]) {
- setCurrentFrame(frames[closestIndex].devices[0]);
- setCurrentDate(new Date(frames[closestIndex].timestamp));
- }
- };
-
- const handleDateChange = (newDate: Date) => {
- // Ensure we're comparing dates at start of day
- const targetStartOfDay = new Date(
- newDate.getFullYear(),
- newDate.getMonth(),
- newDate.getDate(),
- 0,
- 0,
- 0,
- 0
- );
-
- let closestIndex = 0;
- let closestDiff = Infinity;
-
- frames.forEach((frame, index) => {
- const frameDate = new Date(frame.timestamp);
- const frameStartOfDay = new Date(
- frameDate.getFullYear(),
- frameDate.getMonth(),
- frameDate.getDate(),
- 0,
- 0,
- 0,
- 0
- );
-
- const diff = Math.abs(
- frameStartOfDay.getTime() - targetStartOfDay.getTime()
- );
- if (diff < closestDiff) {
- closestDiff = diff;
- closestIndex = index;
- }
- });
-
- setCurrentIndex(closestIndex);
- if (frames[closestIndex]) {
- setCurrentFrame(frames[closestIndex].devices[0]);
- }
- };
-
- const handleJumpToday = () => {
- jumpToDate(new Date());
- };
-
- // More explicit date handling
- useEffect(() => {
- if (frames[currentIndex]) {
- const frameTimestamp = frames[currentIndex].timestamp;
- const frameDate = new Date(frameTimestamp);
-
- // Force date to start of day to avoid timezone issues
- const localDate = new Date(
- frameDate.getFullYear(),
- frameDate.getMonth(),
- frameDate.getDate(),
- 0,
- 0,
- 0,
- 0
- );
-
- setCurrentDate(localDate);
- }
- }, [currentIndex]);
-
- const animateToIndex = (targetIndex: number, duration: number = 1000) => {
- const startIndex = currentIndex;
- const startTime = performance.now();
-
- const animate = (currentTime: number) => {
- const elapsed = currentTime - startTime;
- const progress = Math.min(elapsed / duration, 1);
-
- // Apply easing
- const easedProgress = easeOutCubic(progress);
-
- // Calculate the current position
- const newIndex = Math.round(
- startIndex + (targetIndex - startIndex) * easedProgress
- );
-
- // Update the frame
- setCurrentIndex(newIndex);
- if (frames[newIndex]) {
- setCurrentFrame(frames[newIndex].devices[0]);
- }
-
- // Continue animation if not complete
- if (progress < 1) {
- requestAnimationFrame(animate);
- }
- };
-
- requestAnimationFrame(animate);
- };
-
- return (
- <TimelineProvider>
- <div
- ref={containerRef}
- className="fixed inset-0 flex flex-col bg-background text-foreground overflow-hidden relative"
- style={{
- height: "100vh",
- overscrollBehavior: "none",
- WebkitUserSelect: "none",
- userSelect: "none",
- MozUserSelect: "none",
- msUserSelect: "none",
- }}
- >
- <div className="absolute top-4 left-1/2 -translate-x-1/2 z-50">
- <div className="flex items-center gap-4">
- <TimelineControls
- currentDate={currentDate}
- onDateChange={handleDateChange}
- onJumpToday={handleJumpToday}
- className="shadow-lg"
- />
- {/* <TimelineSearch2
+ const [currentIndex, setCurrentIndex] = useState(0);
+ const [isAiPanelExpanded, setIsAiPanelExpanded] = useState(false);
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const [aiPanelPosition, setAiPanelPosition] = useState({ x: 0, y: 0 });
+ // const [searchResults, setSearchResults] = useState<number[]>([]);
+ const [startAndEndDates, setStartAndEndDates] = useState<TimeRange>({
+ start: new Date(new Date().setHours(0, 0, 0, 0)),
+ end: new Date(),
+ });
+
+ const { currentFrame, setCurrentFrame } = useCurrentFrame((index) => {
+ setCurrentIndex(index);
+ });
+
+ const { currentDate, setCurrentDate, fetchTimeRange, hasDateBeenFetched } =
+ useTimelineStore();
+
+ const { frames, isLoading, error, message, fetchNextDayData } =
+ useTimelineData(currentDate, (frame) => {
+ setCurrentFrame(frame);
+ });
+
+ const [isFrameCacheEnabled, setIsFrameCacheEnabled] = useState(false);
+
+ useEffect(() => {
+ const checkSettings = async () => {
+ try {
+ const response = await fetch("/api/settings");
+ const settings = await response.json();
+
+ setIsFrameCacheEnabled(settings.enableFrameCache);
+
+ // Only proceed with timeline initialization if frame cache is enabled
+ if (settings.enableFrameCache) {
+ const data = await getStartDate();
+ if (!("error" in data)) {
+ setStartAndEndDates((prev) => ({
+ ...prev,
+ start: data,
+ }));
+ }
+ }
+ } catch (error) {
+ console.error("Failed to load settings:", error);
+ }
+ };
+
+ checkSettings();
+ }, []);
+
+ useEffect(() => {
+ setAiPanelPosition({
+ x: window.innerWidth - 400,
+ y: window.innerHeight / 4,
+ });
+ }, []);
+
+ useEffect(() => {
+ if (!isFrameCacheEnabled) return;
+
+ const startTime = new Date(currentDate);
+ startTime.setHours(0, 0, 0, 0);
+
+ const endTime = new Date(currentDate);
+ if (endTime.getDate() === new Date().getDate()) {
+ endTime.setMinutes(endTime.getMinutes() - 5);
+ } else {
+ endTime.setHours(23, 59, 59, 999);
+ }
+ fetchTimeRange(startTime, endTime);
+ }, [currentDate, isFrameCacheEnabled]);
+
+ useEffect(() => {
+ if (currentFrame) {
+ const frameDate = new Date(currentFrame.timestamp);
+ if (!isSameDay(frameDate, currentDate)) {
+ setCurrentDate(frameDate);
+ }
+ }
+ }, [currentFrame, currentDate]);
+
+ const handleScroll = useMemo(
+ () =>
+ throttle(
+ (e: WheelEvent) => {
+ // Move these checks outside the throttle to improve performance
+ const isWithinAiPanel =
+ e.target instanceof Node &&
+ document.querySelector(".ai-panel")?.contains(e.target);
+ const isWithinAudioPanel =
+ e.target instanceof Node &&
+ document
+ .querySelector(".audio-transcript-panel")
+ ?.contains(e.target);
+ const isWithinTimelineDialog =
+ e.target instanceof Node &&
+ document.querySelector('[role="dialog"]')?.contains(e.target);
+
+ if (isWithinAiPanel || isWithinAudioPanel || isWithinTimelineDialog) {
+ return;
+ }
+
+ e.preventDefault();
+ e.stopPropagation();
+
+ // Calculate scroll intensity based on absolute delta
+ const scrollIntensity = Math.abs(e.deltaY);
+ const direction = -Math.sign(e.deltaY);
+
+ // Change this if you want limit the index change
+ const limitIndexChange = 15;
+
+ // Adjust index change based on scroll intensity
+ const indexChange =
+ direction *
+ Math.min(
+ limitIndexChange,
+ Math.ceil(Math.pow(scrollIntensity / 50, 1.5)),
+ );
+
+ requestAnimationFrame(() => {
+ setCurrentIndex((prevIndex) => {
+ const newIndex = Math.min(
+ Math.max(0, Math.floor(prevIndex + indexChange)),
+ frames.length - 1,
+ );
+
+ if (newIndex !== prevIndex && frames[newIndex]) {
+ setCurrentFrame(frames[newIndex]);
+ }
+
+ return newIndex;
+ });
+ });
+ },
+ 16,
+ { leading: true, trailing: false },
+ ),
+ [frames], // Only depend on frames length changes
+ );
+
+ useEffect(() => {
+ const preventScroll = (e: WheelEvent) => {
+ const isWithinAiPanel = document
+ .querySelector(".ai-panel")
+ ?.contains(e.target as Node);
+ const isWithinAudioPanel = document
+ .querySelector(".audio-transcript-panel")
+ ?.contains(e.target as Node);
+ const isWithinTimelineDialog = document
+ .querySelector('[role="dialog"]')
+ ?.contains(e.target as Node);
+
+ if (!isWithinAiPanel && !isWithinAudioPanel && !isWithinTimelineDialog) {
+ e.preventDefault();
+ }
+ };
+
+ document.addEventListener("wheel", preventScroll, { passive: false });
+ return () => document.removeEventListener("wheel", preventScroll);
+ }, []);
+
+ const handleRefresh = () => {
+ window.location.reload();
+ };
+
+ useEffect(() => {
+ const container = containerRef.current;
+ if (container) {
+ container.addEventListener("wheel", handleScroll, { passive: false });
+ }
+
+ return () => {
+ if (container) {
+ container.removeEventListener("wheel", handleScroll);
+ }
+ };
+ }, [handleScroll]);
+
+ const jumpToTime = (targetDate: Date) => {
+ // Find the closest frame to the target date
+ if (frames.length === 0) return;
+
+ const targetTime = targetDate.getTime();
+ let closestIndex = 0;
+ let closestDiff = Infinity;
+
+ frames.forEach((frame, index) => {
+ const frameTime = new Date(frame.timestamp).getTime();
+ const diff = Math.abs(frameTime - targetTime);
+ if (diff < closestDiff) {
+ closestDiff = diff;
+ closestIndex = index;
+ }
+ });
+
+ // Update cursor position
+ setCurrentIndex(closestIndex);
+ if (frames[closestIndex]) {
+ setCurrentFrame(frames[closestIndex]);
+ // setCurrentDate(new Date(frames[closestIndex].timestamp));
+ }
+ };
+
+ const handleDateChange = (newDate: Date) => {
+ console.log(hasDateBeenFetched(newDate));
+ if (!hasDateBeenFetched(newDate)) {
+ setCurrentFrame(null);
+ const frameTimeStamp = new Date(newDate);
+ if (frameTimeStamp.getDate() === new Date(currentDate).getDate()) {
+ return;
+ }
+
+ if (isAfter(startAndEndDates.start.getDate(), newDate.getDate())) {
+ return;
+ }
+
+ setCurrentDate(newDate);
+ } else {
+ jumpToTime(newDate);
+ }
+ };
+
+ const handleJumpToday = () => {
+ window.location.reload();
+ };
+
+ const animateToIndex = (targetIndex: number, duration: number = 1000) => {
+ const startIndex = currentIndex;
+ const startTime = performance.now();
+
+ const animate = (currentTime: number) => {
+ const elapsed = currentTime - startTime;
+ const progress = Math.min(elapsed / duration, 1);
+
+ // Apply easing
+ const easedProgress = easeOutCubic(progress);
+
+ // Calculate the current position
+ const newIndex = Math.round(
+ startIndex + (targetIndex - startIndex) * easedProgress,
+ );
+
+ // Update the frame
+ setCurrentIndex(newIndex);
+ if (frames[newIndex]) {
+ setCurrentFrame(frames[newIndex]);
+ }
+
+ // Continue animation if not complete
+ if (progress < 1) {
+ requestAnimationFrame(animate);
+ }
+ };
+
+ requestAnimationFrame(animate);
+ };
+
+ useEffect(() => {
+ console.log(isLoading);
+ }, [isLoading]);
+
+ return (
+ <TimelineProvider>
+ {!isFrameCacheEnabled ? (
+ <div className="flex items-center justify-center h-screen">
+ <div className="text-center space-y-4">
+ <h2 className="text-xl font-medium">Frame Cache Disabled</h2>
+ <p className="text-muted-foreground">
+ Please enable frame cache in settings to use the timeline feature.
+ </p>
+ </div>
+ </div>
+ ) : (
+ <div
+ ref={containerRef}
+ className="inset-0 flex flex-col bg-background text-foreground relative"
+ style={{
+ height: "100vh",
+ overscrollBehavior: "none",
+ WebkitUserSelect: "none",
+ userSelect: "none",
+ MozUserSelect: "none",
+ msUserSelect: "none",
+ }}
+ >
+ <div className="absolute top-4 left-1/2 -translate-x-1/2 z-50">
+ <div className="flex items-center gap-4">
+ <TimelineControls
+ currentDate={currentDate}
+ startAndEndDates={startAndEndDates}
+ onDateChange={handleDateChange}
+ onJumpToday={handleJumpToday}
+ className="shadow-lg"
+ />
+ {/* <TimelineSearch2
frames={frames}
onResultSelect={animateToIndex}
onSearchResults={setSearchResults}
/> */}
- </div>
- </div>
-
- <div className="flex-1 relative min-h-0">
- {isLoading && (
- <div className="absolute inset-0 flex items-center justify-center">
- <div className="bg-background/90 p-5 border rounded-lg shadow-lg text-center">
- <p>loading frames...</p>
- <Loader2 className="h-4 w-4 animate-spin mx-auto mt-2" />
- </div>
- </div>
- )}
- {message && (
- <div className="absolute inset-0 flex items-center justify-center">
- <div className="bg-background/90 p-5 border rounded-lg shadow-lg text-center">
- <p>{message}</p>
- <Loader2 className="h-4 w-4 animate-spin mx-auto mt-2" />
- </div>
- </div>
- )}
- {error && (
- <div className="absolute inset-0 flex items-center justify-center">
- <div className="bg-destructive/10 p-5 border-destructive/20 border rounded-lg text-destructive flex flex-col items-center">
- <AlertCircle className="h-4 w-4 mb-2" />
- <p className="mb-4">
- i cannot reach your screenpipe data, did you enable the
- timeline feature?
- </p>
- <button
- onClick={handleRefresh}
- className="flex items-center gap-2 px-4 py-2 bg-background text-foreground hover:bg-muted transition-colors rounded-md border border-input"
- >
- <RotateCcw className="h-4 w-4" />
- reload
- </button>
- </div>
- </div>
- )}
- {currentFrame && (
- <img
- src={`data:image/png;base64,${currentFrame.frame}`}
- className="absolute inset-0 w-4/5 h-auto max-h-[75vh] object-contain mx-auto border rounded-xl p-2 mt-20"
- alt="Current frame"
- />
- )}
- {currentFrame && (
- <AudioTranscript
- frames={frames}
- currentIndex={currentIndex}
- groupingWindowMs={30000} // 30 seconds window
- />
- )}
- </div>
-
- <div className="w-4/5 mx-auto my-8 relative select-none">
- <div
- className="h-[60px] bg-card border rounded-lg shadow-sm cursor-crosshair relative overflow-hidden"
- style={{
- width: "100%",
- boxSizing: "border-box",
- }}
- >
- {loadedTimeRange && (
- <TimelineSelection loadedTimeRange={loadedTimeRange} />
- )}
- <div
- className="absolute top-0 h-full w-1 bg-foreground/50 shadow-sm opacity-80"
- style={{ left: `${timePercentage}%`, zIndex: 5 }}
- >
- <div className="relative -top-6 right-3 text-[10px] text-muted-foreground whitespace-nowrap">
- {currentIndex < frames.length &&
- frames[currentIndex] &&
- frames[currentIndex].timestamp &&
- (() => {
- try {
- return new Date(
- frames[currentIndex].timestamp
- ).toLocaleTimeString(
- "en-US", // explicitly specify locale
- {
- hour: "2-digit",
- minute: "2-digit",
- second: "2-digit",
- }
- );
- } catch (e) {
- console.error("failed to format timestamp:", e);
- return frames[currentIndex].timestamp; // fallback to raw timestamp
- }
- })()}
- </div>
- </div>
-
- {searchResults.map((frameIndex) => {
- const percentage = (frameIndex / (frames.length - 1)) * 100;
- return (
- <div
- key={frameIndex}
- className="absolute top-0 h-full w-1.5 bg-blue-500/50 hover:bg-blue-500 cursor-pointer transition-colors"
- style={{ left: `${percentage}%`, zIndex: 4 }}
- onClick={() => {
- animateToIndex(frameIndex);
- setSearchResults([]); // Clear results after clicking
- }}
- >
- <div className="absolute -top-6 -left-2 text-[10px] text-blue-500 whitespace-nowrap">
- {new Date(frames[frameIndex].timestamp).toLocaleTimeString(
- [],
- {
- hour: "2-digit",
- minute: "2-digit",
- }
- )}
- </div>
- </div>
- );
- })}
- </div>
-
- <AIPanel
- position={aiPanelPosition}
- onPositionChange={setAiPanelPosition}
- onClose={() => {
- setIsAiPanelExpanded(false);
- }}
- frames={frames}
- agents={AGENTS}
- isExpanded={isAiPanelExpanded}
- onExpandedChange={setIsAiPanelExpanded}
- />
-
- {loadedTimeRange && frames.length > 0 && (
- <TimelineIconsSection blocks={frames} />
- )}
-
- <div className="relative mt-1 px-2 text-[10px] text-muted-foreground select-none">
- {Array(8)
- .fill(0)
- .map((_, i) => {
- if (!loadedTimeRange) return null;
- const totalDays = 7;
- const daysPerStep = totalDays / 7;
- const date = new Date(
- loadedTimeRange.start.getTime() +
- i * daysPerStep * 24 * 60 * 60 * 1000
- );
- return (
- <div
- key={i}
- className="absolute transform -translate-x-1/2"
- style={{ left: `${(i * 100) / 7}%` }}
- >
- {date.toLocaleDateString([], {
- weekday: "short",
- month: "short",
- day: "numeric",
- })}
- </div>
- );
- })}
- </div>
- </div>
-
- <div className="fixed left-12 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">
- <div className="flex flex-col items-center gap-1">
- <span>▲</span>
- <span>scroll</span>
- <span>▼</span>
- </div>
- </div>
- </div>
- </TimelineProvider>
- );
+ </div>
+ </div>
+
+ <div className="flex-1 relative min-h-0">
+ {isLoading && (
+ <div className="absolute inset-0 flex items-center justify-center backdrop-blur-sm">
+ <div className="bg-background/95 p-6 border rounded-xl shadow-lg text-center space-y-3 max-w-md mx-4">
+ <h3 className="font-medium">Loading Timeline</h3>
+ <p className="text-sm text-muted-foreground">
+ Fetching your recorded frames...
+ </p>
+ <Loader2 className="h-5 w-5 animate-spin mx-auto mt-2" />
+ </div>
+ </div>
+ )}
+
+ {!error && message && (
+ <div className="absolute inset-0 flex items-center justify-center backdrop-blur-sm">
+ <div className="bg-background/95 p-6 border rounded-xl shadow-lg text-center space-y-3 max-w-md mx-4">
+ <h3 className="font-medium">Processing</h3>
+ <p className="text-sm text-muted-foreground">{message}</p>
+ <Loader2 className="h-5 w-5 animate-spin mx-auto mt-2" />
+ </div>
+ </div>
+ )}
+
+ {error && (
+ <div className="absolute inset-0 flex items-center justify-center backdrop-blur-sm">
+ <div className="bg-destructive/5 p-6 border-destructive/20 border rounded-xl text-center space-y-4 max-w-md mx-4">
+ <div className="flex flex-col items-center gap-2">
+ <AlertCircle className="h-6 w-6 text-destructive" />
+ <h3 className="font-medium text-destructive">
+ Connection Error
+ </h3>
+ </div>
+ <p className="text-sm text-muted-foreground">
+ Unable to reach your screenpipe data. Please verify that the
+ screenpipe turned on.
+ </p>
+ <button
+ onClick={handleRefresh}
+ className="flex items-center gap-2 px-4 py-2 bg-background hover:bg-muted transition-colors rounded-lg border border-input mx-auto"
+ >
+ <RotateCcw className="h-4 w-4" />
+ <span>Reload Timeline</span>
+ </button>
+ </div>
+ </div>
+ )}
+ {currentFrame && (
+ <img
+ //src={`data:image/png;base64,${imageFrame}`}
+ src={`http://localhost:3030/frames/${currentFrame.devices[0].frame_id}`}
+ className="absolute inset-0 w-4/5 h-auto max-h-[75vh] object-contain mx-auto border rounded-xl p-2 mt-20"
+ alt="Current frame"
+ />
+ )}
+ {currentFrame && (
+ <AudioTranscript
+ frames={frames}
+ currentIndex={currentIndex}
+ groupingWindowMs={30000} // 30 seconds window
+ />
+ )}
+ </div>
+
+ <TimelineSlider
+ frames={frames}
+ currentIndex={currentIndex}
+ onFrameChange={(index) => {
+ setCurrentIndex(index);
+ if (frames[index]) {
+ setCurrentFrame(frames[index]);
+ }
+ }}
+ fetchNextDayData={fetchNextDayData}
+ currentDate={currentDate}
+ startAndEndDates={startAndEndDates}
+ />
+
+ <AIPanel
+ position={aiPanelPosition}
+ onPositionChange={setAiPanelPosition}
+ onClose={() => {
+ setIsAiPanelExpanded(false);
+ }}
+ frames={frames}
+ agents={AGENTS}
+ isExpanded={isAiPanelExpanded}
+ onExpandedChange={setIsAiPanelExpanded}
+ />
+
+ <div className="fixed left-12 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">
+ <div className="flex flex-col items-center gap-1">
+ <span>▲</span>
+ <span>scroll</span>
+ <span>▼</span>
+ </div>
+ </div>
+ </div>
+ )}
+ </TimelineProvider>
+ );
}
diff --git a/pipes/rewind/src/components/timeline/ai-panel.tsx b/pipes/rewind/src/components/timeline/ai-panel.tsx
index fb97b84c2..1c1a53c98 100644
--- a/pipes/rewind/src/components/timeline/ai-panel.tsx
+++ b/pipes/rewind/src/components/timeline/ai-panel.tsx
@@ -12,445 +12,448 @@ import { Agent } from "./agents";
import { pipe, type Settings } from "@screenpipe/browser";
import { useAiProvider } from "@/lib/hooks/use-ai-provider";
import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
} from "@/components/ui/tooltip";
import { useSettings } from "@/lib/hooks/use-settings";
interface AIPanelProps {
- position: { x: number; y: number };
- onPositionChange: (pos: { x: number; y: number }) => void;
- onClose: () => void;
- frames: StreamTimeSeriesResponse[];
- agents: Agent[];
- isExpanded: boolean;
- onExpandedChange: (expanded: boolean) => void;
+ position: { x: number; y: number };
+ onPositionChange: (pos: { x: number; y: number }) => void;
+ onClose: () => void;
+ frames: StreamTimeSeriesResponse[];
+ agents: Agent[];
+ isExpanded: boolean;
+ onExpandedChange: (expanded: boolean) => void;
}
export function AIPanel({
- position,
- onPositionChange,
- onClose,
- frames,
- agents,
- isExpanded,
- onExpandedChange,
+ position,
+ onPositionChange,
+ onClose,
+ frames,
+ agents,
+ isExpanded,
+ onExpandedChange,
}: AIPanelProps) {
- const { settings } = useSettings();
- const [chatMessages, setChatMessages] = useState<Array<Message>>([]);
- const [isAiLoading, setIsAiLoading] = useState(false);
- const [isStreaming, setIsStreaming] = useState(false);
- const [aiInput, setAiInput] = useState("");
- const [selectedAgent, setSelectedAgent] = useState<Agent>(agents[0]);
- const [isDraggingPanel, setIsDraggingPanel] = useState(false);
- const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
- const [chatWindowSize, setChatWindowSize] = useState({
- width: 400,
- height: 500,
- });
- const [osType, setOsType] = useState<string>("");
-
- const inputRef = useRef<HTMLInputElement>(null);
- const aiPanelRef = useRef<HTMLDivElement>(null);
- const resizerRef = useRef<HTMLDivElement | null>(null);
- const { toast } = useToast();
- const { selectionRange, setSelectionRange } = useTimelineSelection();
- const { isAvailable, error } = useAiProvider(settings);
-
- // Add abort controller ref
- const abortControllerRef = useRef<AbortController | null>(null);
-
- useEffect(() => {
- const detectOS = () => {
- // Try using modern API first
- if ("userAgentData" in navigator) {
- // @ts-ignore - userAgentData is not yet in all TypeScript definitions
- return navigator.userAgentData.platform;
- }
- // Fallback to user agent string parsing
- const userAgent = window.navigator.userAgent.toLowerCase();
- if (userAgent.includes("mac")) return "macos";
- if (userAgent.includes("win")) return "windows";
- if (userAgent.includes("linux")) return "linux";
- return "unknown";
- };
-
- setOsType(detectOS());
- }, []);
-
- const handlePanelMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
- e.preventDefault();
- setIsDraggingPanel(true);
- setDragOffset({
- x: e.clientX - position.x,
- y: e.clientY - position.y,
- });
- };
-
- useEffect(() => {
- const handleGlobalMouseMove = (e: MouseEvent) => {
- if (isDraggingPanel) {
- e.preventDefault();
- const newX = e.clientX - dragOffset.x;
- const newY = e.clientY - dragOffset.y;
-
- const maxX = window.innerWidth - chatWindowSize.width;
- const maxY = window.innerHeight - chatWindowSize.height;
-
- onPositionChange({
- x: Math.max(0, Math.min(maxX, newX)),
- y: Math.max(0, Math.min(maxY, newY)),
- });
- }
- };
-
- const handleGlobalMouseUp = () => {
- setIsDraggingPanel(false);
- };
-
- if (isDraggingPanel) {
- document.addEventListener("mousemove", handleGlobalMouseMove);
- document.addEventListener("mouseup", handleGlobalMouseUp);
- }
-
- return () => {
- document.removeEventListener("mousemove", handleGlobalMouseMove);
- document.removeEventListener("mouseup", handleGlobalMouseUp);
- };
- }, [
- isDraggingPanel,
- dragOffset,
- chatWindowSize.width,
- chatWindowSize.height,
- onPositionChange,
- ]);
-
- // Add keyboard shortcut handler
- useEffect(() => {
- const handleKeyDown = (e: KeyboardEvent) => {
- if (
- (e.metaKey || e.ctrlKey) &&
- e.key.toLowerCase() === "k" &&
- !isExpanded
- ) {
- e.preventDefault();
- onExpandedChange(true);
- setTimeout(() => {
- inputRef.current?.focus();
- }, 100);
- }
- };
-
- window.addEventListener("keydown", handleKeyDown);
- return () => window.removeEventListener("keydown", handleKeyDown);
- }, [isExpanded, onExpandedChange]);
-
- const handleMouseDown = (e: React.MouseEvent) => {
- e.preventDefault();
- const startX = e.clientX;
- const startY = e.clientY;
- const startWidth = chatWindowSize.width;
- const startHeight = chatWindowSize.height;
-
- const handleMouseMove = (moveEvent: MouseEvent) => {
- const newWidth = Math.max(200, startWidth + moveEvent.clientX - startX);
- const newHeight = Math.max(200, startHeight + moveEvent.clientY - startY);
- setChatWindowSize({ width: newWidth, height: newHeight });
- };
-
- const handleMouseUp = () => {
- document.removeEventListener("mousemove", handleMouseMove);
- document.removeEventListener("mouseup", handleMouseUp);
- };
-
- document.addEventListener("mousemove", handleMouseMove);
- document.addEventListener("mouseup", handleMouseUp);
- };
-
- const handleAgentChange = (agentId: string) => {
- const newAgent = agents.find((a) => a.id === agentId) || agents[0];
-
- setSelectedAgent(newAgent);
- };
-
- const handleClose = () => {
- // Abort any ongoing request
- if (abortControllerRef.current) {
- abortControllerRef.current.abort();
- abortControllerRef.current = null;
- }
- setIsAiLoading(false);
- setIsStreaming(false);
- setChatMessages([]);
- setAiInput("");
- onClose();
- setSelectionRange(null);
- };
-
- const handleStopStreaming = () => {
- if (abortControllerRef.current) {
- abortControllerRef.current.abort();
- abortControllerRef.current = null;
- setIsStreaming(false);
- setIsAiLoading(false);
- }
- };
-
- const handleAiSubmit = async (e: React.FormEvent) => {
- pipe.captureMainFeatureEvent("rewind-ai-panel", {
- action: "ai-submit",
- });
- e.preventDefault();
- if (!selectionRange || !aiInput.trim()) return;
-
- // Create new abort controller for this request
- abortControllerRef.current = new AbortController();
-
- const userMessage = {
- id: generateId(),
- role: "user" as const,
- content: aiInput,
- };
- setChatMessages((prev) => [...prev, userMessage]);
- setAiInput("");
- setIsAiLoading(true);
- setIsStreaming(true);
-
- try {
- const relevantFrames = frames.filter((frame) => {
- const frameTime = new Date(frame.timestamp);
- return (
- frameTime >= selectionRange.start && frameTime <= selectionRange.end
- );
- });
-
- const openai = new OpenAI({
- apiKey:
- settings.aiProviderType === "screenpipe-cloud"
- ? settings.user.token
- : settings.openaiApiKey,
- baseURL: settings.aiUrl,
- dangerouslyAllowBrowser: true,
- });
-
- let currentResponse = "";
- setChatMessages((prev) => [
- ...prev,
- { id: generateId(), role: "assistant", content: "" },
- ]);
-
- await selectedAgent.analyze(
- relevantFrames,
- openai,
- {
- model: settings.aiModel,
- onProgress: (chunk) => {
- currentResponse = chunk;
- setChatMessages((prev) => [
- ...prev.slice(0, -1),
- { id: generateId(), role: "assistant", content: currentResponse },
- ]);
- },
- signal: abortControllerRef.current.signal,
- },
- aiInput
- );
- } catch (error) {
- // Only show error if not aborted
- if (!(error instanceof Error && error.name === "AbortError")) {
- console.error("Error generating AI response:", error);
- toast({
- title: "error",
- description: "failed to generate AI response. please try again.",
- variant: "destructive",
- });
- }
- } finally {
- setIsAiLoading(false);
- setIsStreaming(false);
- abortControllerRef.current = null;
- }
- };
-
- if (!selectionRange) return null;
-
- return (
- <div
- ref={aiPanelRef}
- className="ai-panel bg-background border border-muted-foreground rounded-lg shadow-lg transition-all duration-300 ease-in-out z-[100]"
- style={{
- position: "fixed",
- left: position.x,
- top: position.y,
- width: chatWindowSize.width,
- height: isExpanded ? chatWindowSize.height : 120,
- cursor: isDraggingPanel ? "grabbing" : "default",
- }}
- >
- <div
- className="select-none cursor-grab active:cursor-grabbing"
- onMouseDown={handlePanelMouseDown}
- >
- <div className="p-4 border-b border-muted-foreground flex justify-between items-center group">
- <div className="flex items-center gap-2 flex-1">
- <GripHorizontal className="w-4 h-4 text-muted-foreground group-hover:text-foreground" />
- <div className="text-muted-foreground text-xs">
- {new Date(selectionRange.start).toLocaleString([], {
- month: "short",
- day: "numeric",
- hour: "2-digit",
- minute: "2-digit",
- second: "2-digit",
- })}
- {" - "}
- {new Date(selectionRange.end).toLocaleString([], {
- month: "short",
- day: "numeric",
- hour: "2-digit",
- minute: "2-digit",
- second: "2-digit",
- })}
- </div>
- </div>
- <button
- onClick={handleClose}
- className="text-muted-foreground hover:text-foreground transition-colors ml-2"
- >
- <X className="h-4 w-4" />
- </button>
- </div>
-
- {!isExpanded && (
- <div className="p-4">
- <button
- className="px-3 py-1 bg-background hover:bg-accent border text-foreground text-xs rounded flex items-center gap-2 transition-colors"
- onClick={(e) => {
- e.stopPropagation();
- onExpandedChange(true);
- setTimeout(() => {
- inputRef.current?.focus();
- }, 100);
- }}
- >
- <span>ask ai</span>
- <span className="text-muted-foreground text-[10px]">
- {osType === "macos" ? "⌘K" : "Ctrl+K"}
- </span>
- </button>
- </div>
- )}
- </div>
-
- {isExpanded && (
- <div className="flex flex-col h-[calc(100%-52px)]">
- <div
- className="flex-1 overflow-y-auto p-4 space-y-4 min-h-0 hover:cursor-auto text-foreground font-mono text-sm leading-relaxed "
- style={{
- WebkitUserSelect: "text",
- userSelect: "text",
- MozUserSelect: "text",
- msUserSelect: "text",
- overscrollBehavior: "contain",
- overflowY: "scroll",
- height: "100%",
- maxWidth: "100%",
- boxSizing: "border-box",
- }}
- >
- {chatMessages.map((msg, index) => (
- <ChatMessage key={index} message={msg} />
- ))}
- {isAiLoading && (
- <div className="flex justify-center">
- <Loader2 className="h-6 w-6 animate-spin text-foreground" />
- </div>
- )}
- </div>
-
- <form
- onSubmit={handleAiSubmit}
- className="p-3 border-t border-muted-foreground"
- >
- <div className="flex flex-col gap-2">
- <div className="flex items-center gap-2">
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger>
- <Bot className="h-4 w-4 text-muted-foreground" />
- </TooltipTrigger>
- <TooltipContent>
- <p className="text-xs">using {settings.aiModel}</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- <select
- value={selectedAgent.id}
- onChange={(e) => handleAgentChange(e.target.value)}
- className="w-full bg-background border border-muted-foreground text-foreground rounded px-2 py-1 text-xs"
- >
- {agents.map((agent) => (
- <option
- key={agent.id}
- value={agent.id}
- className="bg-background text-foreground"
- >
- {agent.name} - {agent.description}
- </option>
- ))}
- </select>
- </div>
- <div className="flex gap-2">
- <TooltipProvider>
- <Tooltip open={!isAvailable}>
- <TooltipTrigger asChild>
- <div className="flex-1">
- <Input
- ref={inputRef}
- type="text"
- value={aiInput}
- onChange={(e) => setAiInput(e.target.value)}
- placeholder="ask about this time range..."
- className="flex-1 bg-background border border-muted-foreground text-foreground placeholder-muted-foreground"
- disabled={isAiLoading || !isAvailable}
- />
- </div>
- </TooltipTrigger>
- <TooltipContent side="top">
- <p className="text-sm text-destructive">{error}</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- <Button
- type="submit"
- variant="outline"
- className="hover:bg-accent transition-colors"
- disabled={!isAvailable}
- onClick={isStreaming ? handleStopStreaming : handleAiSubmit}
- >
- {isStreaming ? (
- <Square className="h-4 w-4" />
- ) : (
- <Send className="h-4 w-4" />
- )}
- </Button>
- </div>
- </div>
- </form>
- </div>
- )}
-
- <div
- ref={resizerRef}
- onMouseDown={handleMouseDown}
- className="absolute right-0 bottom-0 w-4 h-4 cursor-se-resize bg-transparent"
- style={{
- borderTopLeftRadius: "4px",
- borderBottomRightRadius: "4px",
- cursor: "se-resize",
- }}
- />
- </div>
- );
+ const { settings } = useSettings();
+ const [chatMessages, setChatMessages] = useState<Array<Message>>([]);
+ const [isAiLoading, setIsAiLoading] = useState(false);
+ const [isStreaming, setIsStreaming] = useState(false);
+ const [aiInput, setAiInput] = useState("");
+ const [selectedAgent, setSelectedAgent] = useState<Agent>(agents[0]);
+ const [isDraggingPanel, setIsDraggingPanel] = useState(false);
+ const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
+ const [chatWindowSize, setChatWindowSize] = useState({
+ width: 400,
+ height: 500,
+ });
+ const [osType, setOsType] = useState<string>("");
+
+ const inputRef = useRef<HTMLInputElement>(null);
+ const aiPanelRef = useRef<HTMLDivElement>(null);
+ const resizerRef = useRef<HTMLDivElement | null>(null);
+ const { toast } = useToast();
+ const { selectionRange, setSelectionRange } = useTimelineSelection();
+ const { isAvailable, error } = useAiProvider(settings);
+
+ // Add abort controller ref
+ const abortControllerRef = useRef<AbortController | null>(null);
+
+ useEffect(() => {
+ const detectOS = () => {
+ // Try using modern API first
+ if ("userAgentData" in navigator) {
+ // @ts-ignore - userAgentData is not yet in all TypeScript definitions
+ return navigator.userAgentData.platform;
+ }
+ // Fallback to user agent string parsing
+ const userAgent = window.navigator.userAgent.toLowerCase();
+ if (userAgent.includes("mac")) return "macos";
+ if (userAgent.includes("win")) return "windows";
+ if (userAgent.includes("linux")) return "linux";
+ return "unknown";
+ };
+
+ setOsType(detectOS());
+ }, []);
+
+ const handlePanelMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
+ e.preventDefault();
+ setIsDraggingPanel(true);
+ setDragOffset({
+ x: e.clientX - position.x,
+ y: e.clientY - position.y,
+ });
+ };
+
+ useEffect(() => {
+ const handleGlobalMouseMove = (e: MouseEvent) => {
+ if (isDraggingPanel) {
+ e.preventDefault();
+ const newX = e.clientX - dragOffset.x;
+ const newY = e.clientY - dragOffset.y;
+
+ const maxX = window.innerWidth - chatWindowSize.width;
+ const maxY = window.innerHeight - chatWindowSize.height;
+
+ onPositionChange({
+ x: Math.max(0, Math.min(maxX, newX)),
+ y: Math.max(0, Math.min(maxY, newY)),
+ });
+ }
+ };
+
+ const handleGlobalMouseUp = () => {
+ setIsDraggingPanel(false);
+ };
+
+ if (isDraggingPanel) {
+ document.addEventListener("mousemove", handleGlobalMouseMove);
+ document.addEventListener("mouseup", handleGlobalMouseUp);
+ }
+
+ return () => {
+ document.removeEventListener("mousemove", handleGlobalMouseMove);
+ document.removeEventListener("mouseup", handleGlobalMouseUp);
+ };
+ }, [
+ isDraggingPanel,
+ dragOffset,
+ chatWindowSize.width,
+ chatWindowSize.height,
+ onPositionChange,
+ ]);
+
+ // Add keyboard shortcut handler
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (
+ (e.metaKey || e.ctrlKey) &&
+ e.key.toLowerCase() === "k" &&
+ !isExpanded
+ ) {
+ e.preventDefault();
+ onExpandedChange(true);
+ setTimeout(() => {
+ inputRef.current?.focus();
+ }, 100);
+ }
+ };
+
+ window.addEventListener("keydown", handleKeyDown);
+ return () => window.removeEventListener("keydown", handleKeyDown);
+ }, [isExpanded, onExpandedChange]);
+
+ const handleMouseDown = (e: React.MouseEvent) => {
+ e.preventDefault();
+ const startX = e.clientX;
+ const startY = e.clientY;
+ const startWidth = chatWindowSize.width;
+ const startHeight = chatWindowSize.height;
+
+ const handleMouseMove = (moveEvent: MouseEvent) => {
+ const newWidth = Math.max(200, startWidth + moveEvent.clientX - startX);
+ const newHeight = Math.max(200, startHeight + moveEvent.clientY - startY);
+ setChatWindowSize({ width: newWidth, height: newHeight });
+ };
+
+ const handleMouseUp = () => {
+ document.removeEventListener("mousemove", handleMouseMove);
+ document.removeEventListener("mouseup", handleMouseUp);
+ };
+
+ document.addEventListener("mousemove", handleMouseMove);
+ document.addEventListener("mouseup", handleMouseUp);
+ };
+
+ const handleAgentChange = (agentId: string) => {
+ const newAgent = agents.find((a) => a.id === agentId) || agents[0];
+
+ setSelectedAgent(newAgent);
+ };
+
+ const handleClose = () => {
+ // Abort any ongoing request
+ if (abortControllerRef.current) {
+ abortControllerRef.current.abort();
+ abortControllerRef.current = null;
+ }
+ setIsAiLoading(false);
+ setIsStreaming(false);
+ setChatMessages([]);
+ setAiInput("");
+ onClose();
+ setSelectionRange(null);
+ };
+
+ const handleStopStreaming = () => {
+ if (abortControllerRef.current) {
+ abortControllerRef.current.abort();
+ abortControllerRef.current = null;
+ setIsStreaming(false);
+ setIsAiLoading(false);
+ }
+ };
+
+ const handleAiSubmit = async (e: React.FormEvent) => {
+ pipe.captureMainFeatureEvent("rewind-ai-panel", {
+ action: "ai-submit",
+ });
+ e.preventDefault();
+ if (!selectionRange || !aiInput.trim()) return;
+
+ // Create new abort controller for this request
+ abortControllerRef.current = new AbortController();
+
+ const userMessage = {
+ id: generateId(),
+ role: "user" as const,
+ content: aiInput,
+ };
+ setChatMessages((prev) => [...prev, userMessage]);
+ setAiInput("");
+ setIsAiLoading(true);
+ setIsStreaming(true);
+
+ try {
+ const relevantFrames = frames.filter((frame) => {
+ const frameTime = new Date(frame.timestamp).getTime();
+ const startTime = new Date(selectionRange.start).getTime();
+ const endTime = new Date(selectionRange.end).getTime();
+
+ const isInRange = frameTime >= startTime && frameTime <= endTime;
+
+ return isInRange;
+ });
+
+ const openai = new OpenAI({
+ apiKey:
+ settings.aiProviderType === "screenpipe-cloud"
+ ? settings.user.token
+ : settings.openaiApiKey,
+ baseURL: settings.aiUrl,
+ dangerouslyAllowBrowser: true,
+ });
+
+ let currentResponse = "";
+ setChatMessages((prev) => [
+ ...prev,
+ { id: generateId(), role: "assistant", content: "" },
+ ]);
+
+ await selectedAgent.analyze(
+ relevantFrames,
+ openai,
+ {
+ model: settings.aiModel,
+ onProgress: (chunk) => {
+ currentResponse = chunk;
+ setChatMessages((prev) => [
+ ...prev.slice(0, -1),
+ { id: generateId(), role: "assistant", content: currentResponse },
+ ]);
+ },
+ signal: abortControllerRef.current.signal,
+ },
+ aiInput,
+ );
+ } catch (error) {
+ // Only show error if not aborted
+ if (!(error instanceof Error && error.name === "AbortError")) {
+ console.error("Error generating AI response:", error);
+ toast({
+ title: "error",
+ description: "failed to generate AI response. please try again.",
+ variant: "destructive",
+ });
+ }
+ } finally {
+ setIsAiLoading(false);
+ setIsStreaming(false);
+ abortControllerRef.current = null;
+ }
+ };
+
+ if (!selectionRange) return null;
+
+ return (
+ <div
+ ref={aiPanelRef}
+ className="ai-panel bg-background border border-muted-foreground rounded-lg shadow-lg transition-all duration-300 ease-in-out z-[100]"
+ style={{
+ position: "fixed",
+ left: position.x,
+ top: position.y,
+ width: chatWindowSize.width,
+ height: isExpanded ? chatWindowSize.height : 120,
+ cursor: isDraggingPanel ? "grabbing" : "default",
+ }}
+ >
+ <div
+ className="select-none cursor-grab active:cursor-grabbing"
+ onMouseDown={handlePanelMouseDown}
+ >
+ <div className="p-4 border-b border-muted-foreground flex justify-between items-center group">
+ <div className="flex items-center gap-2 flex-1">
+ <GripHorizontal className="w-4 h-4 text-muted-foreground group-hover:text-foreground" />
+ <div className="text-muted-foreground text-xs">
+ {new Date(selectionRange.start).toLocaleString([], {
+ month: "short",
+ day: "numeric",
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ })}
+ {" - "}
+ {new Date(selectionRange.end).toLocaleString([], {
+ month: "short",
+ day: "numeric",
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ })}
+ </div>
+ </div>
+ <button
+ onClick={handleClose}
+ className="text-muted-foreground hover:text-foreground transition-colors ml-2"
+ >
+ <X className="h-4 w-4" />
+ </button>
+ </div>
+
+ {!isExpanded && (
+ <div className="p-4">
+ <button
+ className="px-3 py-1 bg-background hover:bg-accent border text-foreground text-xs rounded flex items-center gap-2 transition-colors"
+ onClick={(e) => {
+ e.stopPropagation();
+ onExpandedChange(true);
+ setTimeout(() => {
+ inputRef.current?.focus();
+ }, 100);
+ }}
+ >
+ <span>ask ai</span>
+ <span className="text-muted-foreground text-[10px]">
+ {osType === "macos" ? "⌘K" : "Ctrl+K"}
+ </span>
+ </button>
+ </div>
+ )}
+ </div>
+
+ {isExpanded && (
+ <div className="flex flex-col h-[calc(100%-52px)]">
+ <div
+ className="flex-1 overflow-y-auto p-4 space-y-4 min-h-0 hover:cursor-auto text-foreground font-mono text-sm leading-relaxed "
+ style={{
+ WebkitUserSelect: "text",
+ userSelect: "text",
+ MozUserSelect: "text",
+ msUserSelect: "text",
+ overscrollBehavior: "contain",
+ overflowY: "scroll",
+ height: "100%",
+ maxWidth: "100%",
+ boxSizing: "border-box",
+ }}
+ >
+ {chatMessages.map((msg, index) => (
+ <ChatMessage key={index} message={msg} />
+ ))}
+ {isAiLoading && (
+ <div className="flex justify-center">
+ <Loader2 className="h-6 w-6 animate-spin text-foreground" />
+ </div>
+ )}
+ </div>
+
+ <form
+ onSubmit={handleAiSubmit}
+ className="p-3 border-t border-muted-foreground"
+ >
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center gap-2">
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger>
+ <Bot className="h-4 w-4 text-muted-foreground" />
+ </TooltipTrigger>
+ <TooltipContent>
+ <p className="text-xs">using {settings.aiModel}</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ <select
+ value={selectedAgent.id}
+ onChange={(e) => handleAgentChange(e.target.value)}
+ className="w-full bg-background border border-muted-foreground text-foreground rounded px-2 py-1 text-xs"
+ >
+ {agents.map((agent) => (
+ <option
+ key={agent.id}
+ value={agent.id}
+ className="bg-background text-foreground"
+ >
+ {agent.name} - {agent.description}
+ </option>
+ ))}
+ </select>
+ </div>
+ <div className="flex gap-2">
+ <TooltipProvider>
+ <Tooltip open={!isAvailable}>
+ <TooltipTrigger asChild>
+ <div className="flex-1">
+ <Input
+ ref={inputRef}
+ type="text"
+ value={aiInput}
+ onChange={(e) => setAiInput(e.target.value)}
+ placeholder="ask about this time range..."
+ className="flex-1 bg-background border border-muted-foreground text-foreground placeholder-muted-foreground"
+ disabled={isAiLoading || !isAvailable}
+ />
+ </div>
+ </TooltipTrigger>
+ <TooltipContent side="top">
+ <p className="text-sm text-destructive">{error}</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ <Button
+ type="submit"
+ variant="outline"
+ className="hover:bg-accent transition-colors"
+ disabled={!isAvailable}
+ onClick={isStreaming ? handleStopStreaming : handleAiSubmit}
+ >
+ {isStreaming ? (
+ <Square className="h-4 w-4" />
+ ) : (
+ <Send className="h-4 w-4" />
+ )}
+ </Button>
+ </div>
+ </div>
+ </form>
+ </div>
+ )}
+
+ <div
+ ref={resizerRef}
+ onMouseDown={handleMouseDown}
+ className="absolute right-0 bottom-0 w-4 h-4 cursor-se-resize bg-transparent"
+ style={{
+ borderTopLeftRadius: "4px",
+ borderBottomRightRadius: "4px",
+ cursor: "se-resize",
+ }}
+ />
+ </div>
+ );
}
diff --git a/pipes/rewind/src/components/timeline/audio-transcript.tsx b/pipes/rewind/src/components/timeline/audio-transcript.tsx
index 9e1c83e85..f4fb4d52c 100644
--- a/pipes/rewind/src/components/timeline/audio-transcript.tsx
+++ b/pipes/rewind/src/components/timeline/audio-transcript.tsx
@@ -1,259 +1,304 @@
import { useState, useRef, useMemo, useCallback } from "react";
-import { AudioData, StreamTimeSeriesResponse } from "@/app/page";
+import { AudioData, StreamTimeSeriesResponse, TimeRange } from "@/app/page";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Play, Pause, Volume2, GripHorizontal, X } from "lucide-react";
import { VideoComponent } from "@/components/video";
interface AudioGroup {
- deviceName: string;
- isInput: boolean;
- audioItems: AudioData[];
- startTime: Date;
- endTime: Date;
+ deviceName: string;
+ isInput: boolean;
+ audioItems: AudioData[];
+ startTime: Date;
+ endTime: Date;
}
interface AudioTranscriptProps {
- frames: StreamTimeSeriesResponse[];
- currentIndex: number;
- groupingWindowMs?: number; // how many ms to group audio files together
- onClose?: () => void;
+ frames: StreamTimeSeriesResponse[];
+ currentIndex: number;
+ groupingWindowMs?: number; // how many ms to group audio files together
+ onClose?: () => void;
+}
+
+function formatDurationHuman(durationInSeconds: number): string {
+ const hours = Math.floor(durationInSeconds / 3600);
+ const minutes = Math.floor((durationInSeconds % 3600) / 60);
+ const seconds = Math.floor(durationInSeconds % 60);
+
+ const parts = [];
+ if (hours > 0) parts.push(`${hours}h`);
+ if (minutes > 0) parts.push(`${minutes}m`);
+ if (seconds > 0) parts.push(`${seconds}s`);
+
+ return parts.join(" ");
+}
+
+function calculateTimeRange(
+ startTime: Date,
+ durationInSeconds: number,
+): TimeRange {
+ const endTime = new Date(startTime.getTime() + durationInSeconds * 1000);
+
+ return {
+ start: startTime,
+ end: endTime,
+ };
+}
+
+function formatTimeRange(range: TimeRange): string {
+ const formatOptions: Intl.DateTimeFormatOptions = {
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ // fractionalSecondDigits: 3,
+ };
+
+ return `${range.start.toLocaleTimeString([], formatOptions)} - ${range.end.toLocaleTimeString([], formatOptions)}`;
}
export function AudioTranscript({
- frames,
- currentIndex,
- groupingWindowMs = 30000,
- onClose,
+ frames,
+ currentIndex,
+ groupingWindowMs = 30000,
+ onClose,
}: AudioTranscriptProps) {
- const [playing, setPlaying] = useState<string | null>(null);
- const [position, setPosition] = useState(() => ({
- x: window.innerWidth - 320,
- y: 100,
- }));
- const [isDragging, setIsDragging] = useState(false);
- const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
- const [windowSize, setWindowSize] = useState({ width: 300, height: 500 });
- const resizerRef = useRef<HTMLDivElement | null>(null);
- const panelRef = useRef<HTMLDivElement | null>(null);
-
- // 2. Memoize the audio grouping logic
- const audioGroups = useMemo(() => {
- if (!frames.length) return [];
-
- const currentFrame = frames[currentIndex];
- const currentTime = new Date(currentFrame?.timestamp);
- const windowStart = new Date(currentTime.getTime() - groupingWindowMs);
- const windowEnd = new Date(currentTime.getTime() + groupingWindowMs);
-
- // Get frames within our time window
- const nearbyFrames = frames.filter((frame) => {
- const frameTime = new Date(frame.timestamp);
- return frameTime >= windowStart && frameTime <= windowEnd;
- });
-
- // Check if any nearby frames have audio
- const hasNearbyAudio = nearbyFrames.some((frame) =>
- frame.devices.some((device) => device.audio.length > 0)
- );
-
- // Group audio by device
- const groups = new Map<string, AudioGroup>();
-
- nearbyFrames.forEach((frame) => {
- frame.devices.forEach((device) => {
- device.audio.forEach((audio) => {
- const key = `${audio.device_name}-${audio.is_input}`;
-
- if (!groups.has(key)) {
- groups.set(key, {
- deviceName: audio.device_name,
- isInput: audio.is_input,
- audioItems: [],
- startTime: new Date(frame.timestamp),
- endTime: new Date(frame.timestamp),
- });
- }
-
- const group = groups.get(key)!;
- group.audioItems.push(audio);
-
- // Update time range
- const frameTime = new Date(frame.timestamp);
- if (frameTime < group.startTime) group.startTime = frameTime;
- if (frameTime > group.endTime) group.endTime = frameTime;
- });
- });
- });
-
- return Array.from(groups.values());
- }, [frames, currentIndex, groupingWindowMs]);
-
- // 3. Memoize visibility based on audio groups
- const isVisible = useMemo(() => {
- return audioGroups.length > 0;
- }, [audioGroups]);
-
- // 4. Memoize handlers
- const handlePanelMouseMove = useCallback(
- (e: React.MouseEvent) => {
- if (isDragging) {
- setPosition({
- x: e.clientX - dragOffset.x,
- y: e.clientY - dragOffset.y,
- });
- }
- },
- [isDragging, dragOffset]
- );
-
- const handlePlay = useCallback((audioPath: string) => {
- setPlaying((current) => (current === audioPath ? null : audioPath));
- }, []);
-
- const handlePanelMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
- setIsDragging(true);
- setDragOffset({
- x: e.clientX - position.x,
- y: e.clientY - position.y,
- });
- };
-
- const handlePanelMouseUp = () => {
- if (isDragging) {
- setIsDragging(false);
- }
- };
-
- const handleResizeMouseDown = (e: React.MouseEvent) => {
- e.preventDefault();
- const startX = e.clientX;
- const startY = e.clientY;
- const startWidth = windowSize.width;
- const startHeight = windowSize.height;
-
- const handleMouseMove = (moveEvent: MouseEvent) => {
- const newWidth = Math.max(200, startWidth + moveEvent.clientX - startX);
- const newHeight = Math.max(200, startHeight + moveEvent.clientY - startY);
- setWindowSize({ width: newWidth, height: newHeight });
- };
-
- const handleMouseUp = () => {
- document.removeEventListener("mousemove", handleMouseMove);
- document.removeEventListener("mouseup", handleMouseUp);
- };
-
- document.addEventListener("mousemove", handleMouseMove);
- document.addEventListener("mouseup", handleMouseUp);
- };
-
- const handleClose = (e: React.MouseEvent) => {
- e.stopPropagation();
- onClose?.();
- };
-
- return isVisible ? (
- <div
- ref={panelRef}
- style={{
- position: "fixed",
- left: position.x,
- top: position.y,
- width: windowSize.width,
- height: windowSize.height,
- cursor: isDragging ? "grabbing" : "default",
- }}
- className="audio-transcript-panel bg-background/80 backdrop-blur border border-muted-foreground rounded-lg shadow-lg z-[100] overflow-hidden"
- >
- <div
- className="select-none cursor-grab active:cursor-grabbing p-2 border-b border-muted-foreground"
- onMouseDown={handlePanelMouseDown}
- onMouseMove={handlePanelMouseMove}
- onMouseUp={handlePanelMouseUp}
- onMouseLeave={handlePanelMouseUp}
- >
- <div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
- <div className="flex items-center gap-2">
- <GripHorizontal className="w-4 h-4" />
- <span>audio transcripts</span>
- </div>
- <Button
- variant="ghost"
- size="sm"
- className="h-6 w-6 p-0"
- onClick={handleClose}
- >
- <X className="h-3 w-3" />
- </Button>
- </div>
- </div>
-
- <div
- className="space-y-2 p-2 overflow-y-auto"
- style={{
- height: "calc(100% - 37px)",
- overscrollBehavior: "contain", // Prevent scroll chaining
- WebkitOverflowScrolling: "touch", // Smooth scrolling on iOS
- }}
- >
- {audioGroups.map((group, groupIndex) => (
- <Card key={groupIndex} className="p-4 bg-background/80 backdrop-blur">
- <div className="text-xs text-muted-foreground mb-2">
- {group.deviceName} ({group.isInput ? "input" : "output"})
- <div className="text-[10px]">
- {group.startTime.toLocaleTimeString()} -{" "}
- {group.endTime.toLocaleTimeString()}
- </div>
- </div>
-
- {group.audioItems.map((audio, index) => (
- <div key={index} className="space-y-2 mb-2 last:mb-0">
- <div className="flex items-center gap-2">
- <Button
- variant="ghost"
- size="sm"
- className="h-6 w-6 p-0"
- onClick={() => handlePlay(audio.audio_file_path)}
- >
- {playing === audio.audio_file_path ? (
- <Pause className="h-3 w-3" />
- ) : (
- <Play className="h-3 w-3" />
- )}
- </Button>
- <div className="flex items-center gap-1 text-xs">
- <Volume2 className="h-3 w-3" />
- <span>{Math.round(audio.duration_secs)}s</span>
- </div>
- </div>
-
- {audio.transcription && (
- <div className="text-xs pl-8 text-muted-foreground">
- {audio.transcription}
- </div>
- )}
-
- {playing === audio.audio_file_path && (
- <div className="pl-8">
- <VideoComponent filePath={audio.audio_file_path} />
- </div>
- )}
- </div>
- ))}
- </Card>
- ))}
- </div>
-
- <div
- ref={resizerRef}
- onMouseDown={handleResizeMouseDown}
- className="absolute right-0 bottom-0 w-4 h-4 cursor-se-resize bg-transparent"
- style={{
- borderTopLeftRadius: "4px",
- borderBottomRightRadius: "4px",
- cursor: "se-resize",
- }}
- />
- </div>
- ) : null;
+ const [playing, setPlaying] = useState<string | null>(null);
+ const [position, setPosition] = useState(() => ({
+ x: window.innerWidth - 320,
+ y: 100,
+ }));
+ const [isDragging, setIsDragging] = useState(false);
+ const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
+ const [windowSize, setWindowSize] = useState({ width: 300, height: 500 });
+ const resizerRef = useRef<HTMLDivElement | null>(null);
+ const panelRef = useRef<HTMLDivElement | null>(null);
+
+ // 2. Memoize the audio grouping logic
+ const audioGroups = useMemo(() => {
+ if (!frames.length) return [];
+
+ const currentFrame = frames[currentIndex];
+ const currentTime = new Date(currentFrame?.timestamp);
+ const windowStart = new Date(currentTime.getTime() - groupingWindowMs);
+ const windowEnd = new Date(currentTime.getTime() + groupingWindowMs);
+
+ // Get frames within our time window
+ const nearbyFrames = frames.filter((frame) => {
+ const frameTime = new Date(frame.timestamp);
+ return frameTime >= windowStart && frameTime <= windowEnd;
+ });
+
+ // Check if any nearby frames have audio
+ const hasNearbyAudio = nearbyFrames.some((frame) =>
+ frame.devices.some((device) => device.audio.length > 0),
+ );
+
+ // Group audio by device
+ const groups = new Map<string, AudioGroup>();
+
+ nearbyFrames.forEach((frame) => {
+ frame.devices.forEach((device) => {
+ device.audio.forEach((audio) => {
+ const key = `${audio.device_name}-${audio.is_input}`;
+
+ if (!groups.has(key)) {
+ groups.set(key, {
+ deviceName: audio.device_name,
+ isInput: audio.is_input,
+ audioItems: [],
+ startTime: new Date(frame.timestamp),
+ endTime: new Date(frame.timestamp),
+ });
+ }
+
+ const group = groups.get(key)!;
+ group.audioItems.push(audio);
+
+ // Update time range
+ const frameTime = new Date(frame.timestamp);
+ if (frameTime < group.startTime) group.startTime = frameTime;
+ if (frameTime > group.endTime) group.endTime = frameTime;
+ });
+ });
+ });
+
+ return Array.from(groups.values());
+ }, [frames, currentIndex, groupingWindowMs]);
+
+ // 3. Memoize visibility based on audio groups
+ const isVisible = useMemo(() => {
+ return audioGroups.length > 0;
+ }, [audioGroups]);
+
+ // 4. Memoize handlers
+ const handlePanelMouseMove = useCallback(
+ (e: React.MouseEvent) => {
+ if (isDragging) {
+ setPosition({
+ x: e.clientX - dragOffset.x,
+ y: e.clientY - dragOffset.y,
+ });
+ }
+ },
+ [isDragging, dragOffset],
+ );
+
+ const handlePlay = useCallback((audioPath: string) => {
+ setPlaying((current) => (current === audioPath ? null : audioPath));
+ }, []);
+
+ const handlePanelMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
+ setIsDragging(true);
+ setDragOffset({
+ x: e.clientX - position.x,
+ y: e.clientY - position.y,
+ });
+ };
+
+ const handlePanelMouseUp = () => {
+ if (isDragging) {
+ setIsDragging(false);
+ }
+ };
+
+ const handleResizeMouseDown = (e: React.MouseEvent) => {
+ e.preventDefault();
+ const startX = e.clientX;
+ const startY = e.clientY;
+ const startWidth = windowSize.width;
+ const startHeight = windowSize.height;
+
+ const handleMouseMove = (moveEvent: MouseEvent) => {
+ const newWidth = Math.max(200, startWidth + moveEvent.clientX - startX);
+ const newHeight = Math.max(200, startHeight + moveEvent.clientY - startY);
+ setWindowSize({ width: newWidth, height: newHeight });
+ };
+
+ const handleMouseUp = () => {
+ document.removeEventListener("mousemove", handleMouseMove);
+ document.removeEventListener("mouseup", handleMouseUp);
+ };
+
+ document.addEventListener("mousemove", handleMouseMove);
+ document.addEventListener("mouseup", handleMouseUp);
+ };
+
+ const handleClose = (e: React.MouseEvent) => {
+ e.stopPropagation();
+ onClose?.();
+ };
+
+ return isVisible ? (
+ <div
+ ref={panelRef}
+ style={{
+ position: "fixed",
+ left: position.x,
+ top: position.y,
+ width: windowSize.width,
+ height: windowSize.height,
+ cursor: isDragging ? "grabbing" : "default",
+ }}
+ className="audio-transcript-panel bg-background/80 backdrop-blur border border-muted-foreground rounded-lg shadow-lg z-[100] overflow-hidden"
+ >
+ <div
+ className="select-none cursor-grab active:cursor-grabbing p-2 border-b border-muted-foreground"
+ onMouseDown={handlePanelMouseDown}
+ onMouseMove={handlePanelMouseMove}
+ onMouseUp={handlePanelMouseUp}
+ onMouseLeave={handlePanelMouseUp}
+ >
+ <div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
+ <div className="flex items-center gap-2">
+ <GripHorizontal className="w-4 h-4" />
+ <span>audio transcripts</span>
+ </div>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-6 w-6 p-0"
+ onClick={handleClose}
+ >
+ <X className="h-3 w-3" />
+ </Button>
+ </div>
+ </div>
+
+ <div
+ className="space-y-2 p-2 overflow-y-auto"
+ style={{
+ height: "calc(100% - 37px)",
+ overscrollBehavior: "contain", // Prevent scroll chaining
+ WebkitOverflowScrolling: "touch", // Smooth scrolling on iOS
+ }}
+ >
+ {audioGroups.map((group, groupIndex) => (
+ <Card key={groupIndex} className="p-4 bg-background/80 backdrop-blur">
+ <div className="text-xs text-muted-foreground mb-2">
+ {group.deviceName} ({group.isInput ? "input" : "output"})
+ <div className="text-[10px]">
+ {formatTimeRange(
+ calculateTimeRange(
+ group.startTime,
+ group.audioItems.reduce(
+ (value, item) => value + item.duration_secs,
+ 0,
+ ),
+ ),
+ )}
+ </div>
+ </div>
+
+ {group.audioItems.map((audio, index) => (
+ <div key={index} className="space-y-2 mb-2 last:mb-0">
+ <div className="flex items-center gap-2">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-6 w-6 p-0"
+ onClick={() => handlePlay(audio.audio_file_path)}
+ >
+ {playing === audio.audio_file_path ? (
+ <Pause className="h-3 w-3" />
+ ) : (
+ <Play className="h-3 w-3" />
+ )}
+ </Button>
+ <div className="flex items-center gap-1 text-xs">
+ <Volume2 className="h-3 w-3" />
+ <span>
+ {formatDurationHuman(Math.round(audio.duration_secs))}
+ </span>
+ </div>
+ </div>
+
+ {audio.transcription && (
+ <div className="text-xs pl-8 text-muted-foreground">
+ {audio.transcription}
+ </div>
+ )}
+
+ {playing === audio.audio_file_path && (
+ <div className="pl-8">
+ <VideoComponent filePath={audio.audio_file_path} />
+ </div>
+ )}
+ </div>
+ ))}
+ </Card>
+ ))}
+ </div>
+
+ <div
+ ref={resizerRef}
+ onMouseDown={handleResizeMouseDown}
+ className="absolute right-0 bottom-0 w-4 h-4 cursor-se-resize bg-transparent"
+ style={{
+ borderTopLeftRadius: "4px",
+ borderBottomRightRadius: "4px",
+ cursor: "se-resize",
+ }}
+ />
+ </div>
+ ) : null;
}
diff --git a/pipes/rewind/src/components/timeline/timeline-controls.tsx b/pipes/rewind/src/components/timeline/timeline-controls.tsx
index 494a9cbed..09e0d345b 100644
--- a/pipes/rewind/src/components/timeline/timeline-controls.tsx
+++ b/pipes/rewind/src/components/timeline/timeline-controls.tsx
@@ -1,96 +1,125 @@
"use client";
+
import { Button } from "@/components/ui/button";
import { ChevronLeft, ChevronRight, RefreshCw } from "lucide-react";
-import { format, isAfter, startOfDay } from "date-fns";
+import {
+ endOfDay,
+ format,
+ isAfter,
+ isSameDay,
+ startOfDay,
+ subDays,
+} from "date-fns";
import { cn } from "@/lib/utils";
import { motion, AnimatePresence } from "framer-motion";
+import { useMemo } from "react";
+
+interface TimeRange {
+ start: Date;
+ end: Date;
+}
interface TimelineControlsProps {
- currentDate: Date;
- onDateChange: (date: Date) => void;
- onJumpToday: () => void;
- className?: string;
+ startAndEndDates: TimeRange;
+ currentDate: Date;
+ onDateChange: (date: Date) => void;
+ onJumpToday: () => void;
+ className?: string;
}
export function TimelineControls({
- currentDate,
- onDateChange,
- onJumpToday,
- className,
+ startAndEndDates,
+ currentDate,
+ onDateChange,
+ onJumpToday,
+ className,
}: TimelineControlsProps) {
- const today = startOfDay(new Date());
+ const jumpDay = (days: number) => {
+ const today = new Date();
+
+ const newDate = endOfDay(new Date(currentDate));
+ newDate.setDate(newDate.getDate() + days);
- const jumpDay = (days: number) => {
- const newDate = new Date(currentDate);
- newDate.setDate(newDate.getDate() + days);
+ // Prevent jumping to future dates
+ if (isAfter(newDate.getDate(), today.getDate())) {
+ onDateChange(today);
+ return;
+ }
- // Prevent jumping to future dates
- if (isAfter(newDate, today)) {
- onDateChange(today);
- return;
- }
+ onDateChange(newDate);
+ };
- onDateChange(newDate);
- };
+ // Disable forward button if we're at today
+ const isAtToday = useMemo(
+ () => !isAfter(new Date().getDate(), currentDate.getDate()),
+ [currentDate],
+ );
- // Disable forward button if we're at today
- const isAtToday = startOfDay(currentDate).getTime() === today.getTime();
+ const canGoBack = useMemo(
+ () =>
+ isAfter(
+ startAndEndDates.start.getDate(),
+ subDays(currentDate, 1).getDate(),
+ ),
+ [startAndEndDates.start, currentDate],
+ );
- return (
- <div
- className={cn(
- "flex items-center gap-2 p-2 bg-muted/50 rounded-md",
- className
- )}
- >
- <Button
- variant="ghost"
- size="icon"
- onClick={() => jumpDay(-1)}
- className="h-8 w-8"
- >
- <ChevronLeft className="h-4 w-4" />
- </Button>
+ return (
+ <div
+ className={cn(
+ "flex items-center gap-2 p-2 bg-muted/50 rounded-md",
+ className,
+ )}
+ >
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={() => jumpDay(-1)}
+ className="h-8 w-8"
+ disabled={canGoBack}
+ >
+ <ChevronLeft className="h-4 w-4" />
+ </Button>
- <AnimatePresence mode="wait">
- <motion.div
- key={currentDate.toISOString()}
- initial={{ y: -20, opacity: 0 }}
- animate={{ y: 0, opacity: 1 }}
- exit={{ y: 20, opacity: 0 }}
- transition={{
- type: "spring",
- stiffness: 500,
- damping: 30,
- duration: 0.2,
- }}
- className="bg-background border rounded px-3 py-1 text-sm font-mono"
- >
- {format(currentDate, "d MMM yyyy")}
- </motion.div>
- </AnimatePresence>
+ <AnimatePresence mode="wait">
+ <motion.div
+ key={currentDate.toISOString()}
+ initial={{ y: -20, opacity: 0 }}
+ animate={{ y: 0, opacity: 1 }}
+ exit={{ y: 20, opacity: 0 }}
+ transition={{
+ type: "spring",
+ stiffness: 500,
+ damping: 30,
+ duration: 0.2,
+ }}
+ className="bg-background border rounded px-3 py-1 text-sm font-mono"
+ >
+ {format(currentDate, "d MMM yyyy")}
+ </motion.div>
+ </AnimatePresence>
- <Button
- variant="ghost"
- size="icon"
- onClick={() => jumpDay(1)}
- className="h-8 w-8"
- disabled={isAtToday}
- >
- <ChevronRight className="h-4 w-4" />
- </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={() => jumpDay(1)}
+ className="h-8 w-8"
+ disabled={isAtToday}
+ >
+ <ChevronRight className="h-4 w-4" />
+ </Button>
- <div className="h-4 w-px bg-border mx-2" />
+ <div className="h-4 w-px bg-border mx-2" />
- <Button
- variant="ghost"
- size="icon"
- onClick={onJumpToday}
- className="h-8 w-8"
- disabled={isAtToday}
- >
- <RefreshCw className="h-4 w-4" />
- </Button>
- </div>
- );
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={onJumpToday}
+ className="h-8 w-8"
+ disabled={isAtToday}
+ >
+ <RefreshCw className="h-4 w-4" />
+ </Button>
+ </div>
+ );
}
diff --git a/pipes/rewind/src/components/timeline/timeline-dock-section.tsx b/pipes/rewind/src/components/timeline/timeline-dock-section.tsx
index 2d14b274e..f6b6eb804 100644
--- a/pipes/rewind/src/components/timeline/timeline-dock-section.tsx
+++ b/pipes/rewind/src/components/timeline/timeline-dock-section.tsx
@@ -36,7 +36,7 @@ interface AppIcon {
async function getAppIcon(
appName: string,
- appPath?: string
+ appPath?: string,
): Promise<AppIcon | null> {
const params = new URLSearchParams({
name: appName,
@@ -63,10 +63,16 @@ async function getAppIcon(
}
}
+interface TimeRange {
+ start: Date;
+ end: Date;
+}
export function TimelineIconsSection({
blocks,
+ timeRange,
}: {
blocks: StreamTimeSeriesResponse[];
+ timeRange: TimeRange;
}) {
const [iconCache, setIconCache] = useState<{ [key: string]: string }>({});
const [selectedApp, setSelectedApp] = useState<ProcessedBlock | null>(null);
@@ -76,12 +82,12 @@ export function TimelineIconsSection({
const { setSelectionRange } = useTimelineSelection();
// Separate time range calculation
- const timeRange = useMemo(() => {
- if (blocks.length === 0) return null;
- const startTime = new Date(blocks[blocks.length - 1].timestamp);
- const endTime = new Date(blocks[0].timestamp);
- return { start: startTime, end: endTime };
- }, [blocks]);
+ //const timeRange = useMemo(() => {
+ // if (blocks.length === 0) return null;
+ // const startTime = new Date(blocks[blocks.length - 1].timestamp);
+ // const endTime = new Date(blocks[0].timestamp);
+ // return { start: startTime, end: endTime };
+ //}, [blocks]);
// Process blocks without icon dependency
const { processedBlocks, processedAudioGroups } = useMemo(() => {
@@ -101,8 +107,8 @@ export function TimelineIconsSection({
timeRange.start.getTime()) /
(timeRange.end.getTime() - timeRange.start.getTime())) *
100,
- }))
- )
+ })),
+ ),
)
.filter((audio) => {
const timestamp = audio.timestamp;
@@ -174,7 +180,8 @@ export function TimelineIconsSection({
const blockStart = blockEntries[0].timestamp;
const blockEnd = blockEntries[blockEntries.length - 1].timestamp;
const blockMiddle = new Date(
- blockStart.getTime() + (blockEnd.getTime() - blockStart.getTime()) / 2
+ blockStart.getTime() +
+ (blockEnd.getTime() - blockStart.getTime()) / 2,
);
const windowsInBlock = blockEntries
@@ -257,7 +264,7 @@ export function TimelineIconsSection({
// Fail silently - the UI will just not show an icon
}
},
- [iconCache, iconInvocationCount]
+ [iconCache, iconInvocationCount],
);
useEffect(() => {
diff --git a/pipes/rewind/src/components/timeline/timeline-selection.tsx b/pipes/rewind/src/components/timeline/timeline-selection.tsx
index 81eb94886..d80ccff13 100644
--- a/pipes/rewind/src/components/timeline/timeline-selection.tsx
+++ b/pipes/rewind/src/components/timeline/timeline-selection.tsx
@@ -2,96 +2,96 @@ import { useTimelineSelection } from "@/lib/hooks/use-timeline-selection";
import { useState, useCallback, MouseEvent } from "react";
interface TimelineSelectionProps {
- loadedTimeRange: { start: Date; end: Date };
- numChunks?: number;
+ loadedTimeRange: { start: Date; end: Date };
+ numChunks?: number;
}
export function TimelineSelection({
- loadedTimeRange,
- numChunks = 60,
+ loadedTimeRange,
+ numChunks = 60,
}: TimelineSelectionProps) {
- const { setSelectionRange, selectionRange } = useTimelineSelection();
- const [isDragging, setIsDragging] = useState(false);
- const [currentChunk, setCurrentChunk] = useState<number | null>(null);
- const [startChunk, setStartChunk] = useState<number | null>(null);
+ const { setSelectionRange, selectionRange } = useTimelineSelection();
+ const [isDragging, setIsDragging] = useState(false);
+ const [currentChunk, setCurrentChunk] = useState<number | null>(null);
+ const [startChunk, setStartChunk] = useState<number | null>(null);
- const getDateFromChunk = useCallback(
- (chunkIndex: number) => {
- const totalMs =
- loadedTimeRange.end.getTime() - loadedTimeRange.start.getTime();
- const msPerChunk = totalMs / numChunks;
- return new Date(
- loadedTimeRange.start.getTime() + chunkIndex * msPerChunk
- );
- },
- [loadedTimeRange, numChunks]
- );
+ const getDateFromChunk = useCallback(
+ (chunkIndex: number) => {
+ const totalMs =
+ loadedTimeRange.end.getTime() - loadedTimeRange.start.getTime();
+ const msPerChunk = totalMs / numChunks;
+ return new Date(
+ loadedTimeRange.start.getTime() + chunkIndex * msPerChunk,
+ );
+ },
+ [loadedTimeRange, numChunks],
+ );
- const handleMouseDown = (e: MouseEvent, chunkIndex: number) => {
- e.preventDefault(); // Prevent text selection
- setIsDragging(true);
- setStartChunk(chunkIndex);
- setCurrentChunk(chunkIndex);
- const date = getDateFromChunk(chunkIndex);
- setSelectionRange({ start: date, end: date });
- };
+ const handleMouseDown = (e: MouseEvent, chunkIndex: number) => {
+ e.preventDefault(); // Prevent text selection
+ setIsDragging(true);
+ setStartChunk(chunkIndex);
+ setCurrentChunk(chunkIndex);
+ const date = getDateFromChunk(chunkIndex);
+ setSelectionRange({ start: date, end: date });
+ };
- const handleMouseMove = (e: MouseEvent, chunkIndex: number) => {
- if (!isDragging || startChunk === null) return;
- setCurrentChunk(chunkIndex);
+ const handleMouseMove = (e: MouseEvent, chunkIndex: number) => {
+ if (!isDragging || startChunk === null) return;
+ setCurrentChunk(chunkIndex);
- const start = Math.min(startChunk, chunkIndex);
- const end = Math.max(startChunk, chunkIndex);
+ const start = Math.min(startChunk, chunkIndex);
+ const end = Math.max(startChunk, chunkIndex);
- setSelectionRange({
- start: getDateFromChunk(start),
- end: getDateFromChunk(end + 1), // +1 to include the full chunk
- });
- };
+ setSelectionRange({
+ start: getDateFromChunk(start),
+ end: getDateFromChunk(end + 1), // +1 to include the full chunk
+ });
+ };
- const handleMouseUp = () => {
- setIsDragging(false);
- setStartChunk(null);
- setCurrentChunk(null);
- };
+ const handleMouseUp = () => {
+ setIsDragging(false);
+ setStartChunk(null);
+ setCurrentChunk(null);
+ };
- const isChunkSelected = useCallback(
- (chunkIndex: number) => {
- if (isDragging && startChunk !== null && currentChunk !== null) {
- const start = Math.min(startChunk, currentChunk);
- const end = Math.max(startChunk, currentChunk);
- return chunkIndex >= start && chunkIndex <= end;
- } else if (selectionRange) {
- const chunkDate = getDateFromChunk(chunkIndex);
- const nextChunkDate = getDateFromChunk(chunkIndex + 1);
- return (
- chunkDate >= selectionRange.start && chunkDate < selectionRange.end
- );
- }
- return false;
- },
- [isDragging, startChunk, currentChunk, selectionRange, getDateFromChunk]
- );
+ const isChunkSelected = useCallback(
+ (chunkIndex: number) => {
+ if (isDragging && startChunk !== null && currentChunk !== null) {
+ const start = Math.min(startChunk, currentChunk);
+ const end = Math.max(startChunk, currentChunk);
+ return chunkIndex >= start && chunkIndex <= end;
+ } else if (selectionRange) {
+ const chunkDate = getDateFromChunk(chunkIndex);
+ const nextChunkDate = getDateFromChunk(chunkIndex + 1);
+ return (
+ chunkDate >= selectionRange.start && chunkDate < selectionRange.end
+ );
+ }
+ return false;
+ },
+ [isDragging, startChunk, currentChunk, selectionRange, getDateFromChunk],
+ );
- return (
- <div
- className="absolute inset-0 flex"
- onMouseLeave={handleMouseUp}
- onMouseUp={handleMouseUp}
- >
- {Array.from({ length: numChunks }).map((_, i) => (
- <div
- key={i}
- className={`h-full flex-1 border-r border-foreground/5 transition-colors ${
- isChunkSelected(i) ? "bg-primary/30" : "hover:bg-foreground/10"
- }`}
- style={{
- cursor: isDragging ? "col-resize" : "pointer",
- }}
- onMouseDown={(e) => handleMouseDown(e, i)}
- onMouseMove={(e) => handleMouseMove(e, i)}
- />
- ))}
- </div>
- );
+ return (
+ <div
+ className="absolute inset-0 flex"
+ onMouseLeave={handleMouseUp}
+ onMouseUp={handleMouseUp}
+ >
+ {Array.from({ length: numChunks }).map((_, i) => (
+ <div
+ key={i}
+ className={`h-full flex-1 border-r border-foreground/5 transition-colors ${
+ isChunkSelected(i) ? "bg-primary/30" : "hover:bg-foreground/10"
+ }`}
+ style={{
+ cursor: isDragging ? "col-resize" : "pointer",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, i)}
+ onMouseMove={(e) => handleMouseMove(e, i)}
+ />
+ ))}
+ </div>
+ );
}
diff --git a/pipes/rewind/src/components/timeline/timeline.tsx b/pipes/rewind/src/components/timeline/timeline.tsx
new file mode 100644
index 000000000..f89eec32f
--- /dev/null
+++ b/pipes/rewind/src/components/timeline/timeline.tsx
@@ -0,0 +1,282 @@
+import { StreamTimeSeriesResponse, TimeRange } from "@/app/page";
+import { useTimelineSelection } from "@/lib/hooks/use-timeline-selection";
+import { isAfter, subDays } from "date-fns";
+import { motion, useScroll, useTransform } from "framer-motion";
+import { AudioLinesIcon } from "lucide-react";
+import { useEffect, useMemo, useRef, useState } from "react";
+
+interface TimelineSliderProps {
+ frames: StreamTimeSeriesResponse[];
+ currentIndex: number;
+ startAndEndDates: TimeRange;
+ onFrameChange: (index: number) => void;
+ fetchNextDayData: (date: Date) => void;
+ currentDate: Date;
+ onSelectionChange?: (selectedFrames: StreamTimeSeriesResponse[]) => void;
+}
+
+interface AppGroup {
+ appName: string;
+ frames: StreamTimeSeriesResponse[];
+ color: string;
+ iconSrc?: string;
+}
+
+export function stringToColor(str: string): string {
+ let hash = 0;
+ for (let i = 0; i < str.length; i++) {
+ hash = str.charCodeAt(i) + ((hash << 5) - hash);
+ }
+ let color = "#";
+ for (let i = 0; i < 3; i++) {
+ const value = (hash >> (i * 8)) & 0xff;
+ color += ("00" + value.toString(16)).substr(-2);
+ }
+ return color;
+}
+
+export const TimelineSlider = ({
+ frames,
+ currentIndex,
+ onFrameChange,
+ fetchNextDayData,
+ startAndEndDates,
+ currentDate,
+ onSelectionChange,
+}: TimelineSliderProps) => {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const { scrollXProgress } = useScroll({
+ container: containerRef,
+ offset: ["start end", "end start"],
+ });
+ const lineWidth = useTransform(scrollXProgress, [0, 1], ["0%", "100%"]);
+ const [hoveredTimestamp, setHoveredTimestamp] = useState<string | null>(null);
+ const [isDragging, setIsDragging] = useState(false);
+ const [dragStartIndex, setDragStartIndex] = useState<number | null>(null);
+ const [selectedIndices, setSelectedIndices] = useState<Set<number>>(
+ new Set(),
+ );
+ const { setSelectionRange, selectionRange } = useTimelineSelection();
+
+ const appGroups = useMemo(() => {
+ const groups: AppGroup[] = [];
+ let currentApp = "";
+ let currentGroup: StreamTimeSeriesResponse[] = [];
+
+ frames.forEach((frame) => {
+ const appName = frame.devices[0].metadata.app_name;
+ if (appName !== currentApp) {
+ if (currentGroup.length > 0) {
+ groups.push({
+ appName: currentApp,
+ frames: currentGroup,
+ color: stringToColor(currentApp),
+ });
+ }
+ currentApp = appName;
+ currentGroup = [frame];
+ } else {
+ currentGroup.push(frame);
+ }
+ });
+
+ if (currentGroup.length > 0) {
+ groups.push({
+ appName: currentApp,
+ frames: currentGroup,
+ color: stringToColor(currentApp),
+ });
+ }
+ return groups;
+ }, [frames]);
+
+ // Add effect to keep current frame in view
+ useEffect(() => {
+ const container = containerRef.current;
+ if (!container || !frames[currentIndex]) return;
+
+ const currentTimestamp = frames[currentIndex].timestamp;
+ const currentElement = container.querySelector(
+ `[data-timestamp="${currentTimestamp}"]`,
+ );
+
+ if (!currentElement) return;
+
+ currentElement.scrollIntoView({
+ behavior: "smooth",
+ block: "nearest",
+ inline: "center",
+ });
+ }, [currentIndex, frames.length]);
+
+ useEffect(() => {
+ const container = containerRef.current;
+ if (!container) return;
+
+ const handleScroll = () => {
+ const { scrollLeft, scrollWidth, clientWidth } = container;
+
+ // Check if we're 20% away from the left end (considering RTL)
+ const threshold = scrollWidth * 0.2; // 20% of total scroll width
+ const isNearLeftEnd =
+ Math.abs(scrollLeft) + clientWidth >= scrollWidth - threshold;
+
+ const lastDate = subDays(currentDate, 1);
+ if (isNearLeftEnd && isAfter(lastDate, startAndEndDates.start)) {
+ console.log("fetching next day's data", currentDate);
+ fetchNextDayData(lastDate);
+ }
+ };
+
+ container.addEventListener("scroll", handleScroll);
+ return () => container.removeEventListener("scroll", handleScroll);
+ }, [fetchNextDayData, currentDate, startAndEndDates]);
+
+ useEffect(() => {
+ if (!selectionRange) {
+ setSelectedIndices(new Set());
+ }
+ }, [selectionRange]);
+
+ // Handle drag start
+ const handleDragStart = (index: number) => {
+ setIsDragging(true);
+ setDragStartIndex(index);
+ setSelectedIndices(new Set([index]));
+
+ // Set initial selection range
+ const startDate = new Date(frames[index].timestamp);
+ setSelectionRange({ start: startDate, end: startDate });
+ };
+
+ // Handle drag over
+ const handleDragOver = (index: number) => {
+ if (isDragging && dragStartIndex !== null) {
+ const start = Math.min(dragStartIndex, index);
+ const end = Math.max(dragStartIndex, index);
+ const newSelection = new Set<number>();
+
+ for (let i = start; i <= end; i++) {
+ newSelection.add(i);
+ }
+
+ setSelectedIndices(newSelection);
+
+ // Update selection range
+ setSelectionRange({
+ end: new Date(frames[start].timestamp),
+ start: new Date(frames[end].timestamp),
+ });
+
+ // Notify parent of selection change
+ if (onSelectionChange) {
+ const selectedFrames = Array.from(newSelection).map((i) => frames[i]);
+ onSelectionChange(selectedFrames);
+ }
+ }
+ };
+
+ // Handle drag end
+ const handleDragEnd = () => {
+ setIsDragging(false);
+ setDragStartIndex(null);
+ };
+
+ return (
+ <div className="relative w-full" dir="rtl">
+ <motion.div
+ className="absolute top-0 h-1 bg-blue-500/0"
+ style={{ width: lineWidth }}
+ />
+ <div
+ ref={containerRef}
+ className="w-full overflow-x-auto scroll-smooth scrollbar-hide"
+ style={{
+ scrollBehavior: "auto",
+ }}
+ >
+ <motion.div
+ className="whitespace-nowrap flex flex-nowrap w-max justify-center px-[50vw] h-40 sticky right-0"
+ onMouseUp={handleDragEnd}
+ onMouseLeave={handleDragEnd}
+ >
+ {appGroups.map((group, groupIndex) => (
+ <div
+ key={`${group.appName}-${groupIndex}`}
+ className="flex flex-nowrap items-end h-full group pt-20 relative"
+ dir="rtl"
+ >
+ <div className="absolute top-0 left-1/2 w-5 h-5 rounded-full -translate-x-1/2 bg-background/50 backdrop-blur p-0.5">
+ <img
+ src={`http://localhost:11435/app-icon?name=${group.appName}`}
+ className="w-full h-full opacity-70"
+ alt={group.appName}
+ loading="lazy"
+ decoding="async"
+ />
+ </div>
+ {group.frames.map((frame) => {
+ const frameIndex = frames.indexOf(frame);
+ const isSelected = selectedIndices.has(frameIndex);
+ const frameDate = new Date(frame.timestamp);
+ const isInRange =
+ selectionRange &&
+ frameDate >= selectionRange.start &&
+ frameDate <= selectionRange.end;
+
+ const hasAudio = Boolean(frame.devices[0].audio.length);
+
+ return (
+ <motion.div
+ key={frame.timestamp}
+ data-timestamp={frame.timestamp}
+ className={`flex-shrink-0 cursor-pointer w-2 mx-0.5 rounded-t relative group hover:z-50 ${
+ isSelected || isInRange
+ ? "ring-2 ring-blue-500 ring-offset-1"
+ : ""
+ }`}
+ style={{
+ backgroundColor: group.color,
+ height:
+ frameIndex === currentIndex || isSelected || isInRange
+ ? "100%"
+ : "70%",
+ opacity:
+ frameIndex === currentIndex || isSelected || isInRange
+ ? 1
+ : 0.7,
+ direction: "ltr",
+ }}
+ whileHover={{ height: "100%", opacity: 1 }}
+ onMouseDown={() => handleDragStart(frameIndex)}
+ onMouseEnter={() => {
+ setHoveredTimestamp(frame.timestamp);
+ handleDragOver(frameIndex);
+ }}
+ onMouseLeave={() => setHoveredTimestamp(null)}
+ >
+ {hasAudio && (
+ <div className="absolute -top-5 left-1/2 -translate-x-1/2 w-4 h-4 rounded-full ">
+ <AudioLinesIcon className="w-full h-full" />
+ </div>
+ )}
+ {hoveredTimestamp === frame.timestamp && (
+ <div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-6 w-max bg-background border rounded-md px-2 py-1 text-xs shadow-lg">
+ <p className="font-medium">
+ {frame.devices[0].metadata.app_name}
+ </p>
+ <p className="text-muted-foreground">
+ {new Date(frame.timestamp).toLocaleString()}
+ </p>
+ </div>
+ )}
+ </motion.div>
+ );
+ })}
+ </div>
+ ))}
+ </motion.div>
+ </div>
+ </div>
+ );
+};
diff --git a/pipes/rewind/src/lib/actions/get-start-date.ts b/pipes/rewind/src/lib/actions/get-start-date.ts
new file mode 100644
index 000000000..6781f82d6
--- /dev/null
+++ b/pipes/rewind/src/lib/actions/get-start-date.ts
@@ -0,0 +1,81 @@
+"use server";
+
+import { isAfter } from "date-fns";
+
+export async function getStartDate() {
+ try {
+ const videoChunkQuery = `
+ SELECT
+ f.timestamp,
+ f.offset_index,
+ ot.text,
+ ot.app_name,
+ ot.window_name,
+ vc.device_name as screen_device,
+ vc.file_path as video_path
+ FROM frames f
+ JOIN video_chunks vc ON f.video_chunk_id = vc.id
+ LEFT JOIN ocr_text ot ON f.id = ot.frame_id
+ ORDER BY f.timestamp ASC, f.offset_index ASC
+ LIMIT 1
+
+`;
+
+ const audioChunkQuery = `
+ SELECT
+ at.timestamp,
+ at.transcription,
+ at.device as audio_device,
+ at.is_input_device,
+ ac.file_path as audio_path
+ FROM audio_transcriptions at
+ JOIN audio_chunks ac ON at.audio_chunk_id = ac.id
+ ORDER BY at.timestamp ASC
+ LIMIT 1
+`;
+
+ const videoFetch = fetch("http://localhost:3030/raw_sql", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ query: videoChunkQuery }),
+ });
+
+ const audioFetch = fetch("http://localhost:3030/raw_sql", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ query: audioChunkQuery }),
+ });
+
+ const [videoData, audioData] = await Promise.all([videoFetch, audioFetch]);
+
+ if (!videoData.ok || !audioData.ok) {
+ return {
+ error: "error occured while getting data",
+ video: await videoData.json(),
+ audio: await audioData.json(),
+ query: {
+ videoChunkQuery,
+ audioChunkQuery,
+ },
+ };
+ }
+
+ const video = (await videoData.json())[0];
+ const audio = (await audioData.json())[0];
+
+ const videoStart = new Date(video.timestamp);
+ const audioStart = new Date(audio.timestamp);
+
+ const videoGreater = isAfter(videoStart, audioStart);
+
+ return !videoGreater ? videoStart : audioStart;
+ } catch (e) {
+ return {
+ error: "errro occured",
+ };
+ }
+}
diff --git a/pipes/rewind/src/lib/actions/has-frames-date.ts b/pipes/rewind/src/lib/actions/has-frames-date.ts
new file mode 100644
index 000000000..2bf6d73d4
--- /dev/null
+++ b/pipes/rewind/src/lib/actions/has-frames-date.ts
@@ -0,0 +1,43 @@
+"use server";
+
+export async function hasFramesForDate(date: Date) {
+ try {
+ // Set up start and end of the day
+ const startOfDay = new Date(date);
+ startOfDay.setHours(0, 0, 0, 0);
+
+ const endOfDay = new Date(date);
+ endOfDay.setHours(23, 59, 59, 999);
+
+ const query = `
+ SELECT COUNT(*) as frame_count
+ FROM frames f
+ WHERE f.timestamp >= '${startOfDay.toISOString()}'
+ AND f.timestamp <= '${endOfDay.toISOString()}'
+ LIMIT 1
+ `;
+
+ const response = await fetch("http://localhost:3030/raw_sql", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ query }),
+ });
+
+ if (!response.ok) {
+ return {
+ error: "Error occurred while checking frames",
+ details: await response.json(),
+ };
+ }
+
+ const result = await response.json();
+ return result[0]?.frame_count > 0;
+ } catch (e) {
+ return {
+ error: "Error occurred while checking frames",
+ details: e,
+ };
+ }
+}
diff --git a/pipes/rewind/src/lib/actions/video-actions.ts b/pipes/rewind/src/lib/actions/video-actions.ts
index 9238c9e96..b22f2ee78 100644
--- a/pipes/rewind/src/lib/actions/video-actions.ts
+++ b/pipes/rewind/src/lib/actions/video-actions.ts
@@ -1,35 +1,47 @@
-'use server'
+"use server";
-import { readFile } from 'node:fs/promises'
-import { resolve } from 'node:path'
+import { readFile } from "node:fs/promises";
+import { resolve } from "node:path";
-export async function getMediaFile(filePath: string): Promise<{ data: string; mimeType: string }> {
- try {
- const absolutePath = resolve(filePath)
- const buffer = await readFile(absolutePath)
- // convert to base64
- const data = buffer.toString('base64')
-
- const getMimeType = (path: string): string => {
- const ext = path.split('.').pop()?.toLowerCase()
- const isAudio = path.toLowerCase().includes('input') || path.toLowerCase().includes('output')
-
- switch (ext) {
- case 'mp4': return 'video/mp4'
- case 'webm': return 'video/webm'
- case 'ogg': return 'video/ogg'
- case 'mp3': return 'audio/mpeg'
- case 'wav': return 'audio/wav'
- default: return isAudio ? 'audio/mpeg' : 'video/mp4'
- }
- }
+export async function getMediaFile(
+ filePath: string,
+): Promise<{ data: string; mimeType: string }> {
+ try {
+ const absolutePath = resolve(filePath);
+ const buffer = await readFile(absolutePath);
+ // convert to base64
+ const data = buffer.toString("base64");
- return {
- data,
- mimeType: getMimeType(filePath)
- }
- } catch (error) {
- console.error('failed to read media file:', error)
- throw new Error(`failed to read media file: ${error instanceof Error ? error.message : 'unknown error'}`)
- }
+ const getMimeType = (path: string): string => {
+ const ext = path.split(".").pop()?.toLowerCase();
+ const isAudio =
+ path.toLowerCase().includes("input") ||
+ path.toLowerCase().includes("output");
+
+ switch (ext) {
+ case "mp4":
+ return "video/mp4";
+ case "webm":
+ return "video/webm";
+ case "ogg":
+ return "video/ogg";
+ case "mp3":
+ return "audio/mpeg";
+ case "wav":
+ return "audio/wav";
+ default:
+ return isAudio ? "audio/mpeg" : "video/mp4";
+ }
+ };
+
+ return {
+ data,
+ mimeType: getMimeType(filePath),
+ };
+ } catch (error) {
+ console.error("failed to read media file:", error);
+ throw new Error(
+ `failed to read media file: ${error instanceof Error ? error.message : "unknown error"}`,
+ );
+ }
}
diff --git a/pipes/rewind/src/lib/hooks/use-current-frame.tsx b/pipes/rewind/src/lib/hooks/use-current-frame.tsx
new file mode 100644
index 000000000..7baeb95ff
--- /dev/null
+++ b/pipes/rewind/src/lib/hooks/use-current-frame.tsx
@@ -0,0 +1,24 @@
+import { StreamTimeSeriesResponse } from "@/app/page";
+import { useEffect, useRef, useState } from "react";
+import { useTimelineStore } from "./use-timeline-store";
+
+export const useCurrentFrame = (setCurrentIndex: (index: number) => void) => {
+ const [currentFrame, setCurrentFrame] =
+ useState<StreamTimeSeriesResponse | null>(null);
+
+ const { frames, isLoading } = useTimelineStore();
+ const lastFramesLen = useRef<number>(0);
+
+ useEffect(() => {
+ if (!currentFrame && frames.length) {
+ setCurrentFrame(frames[lastFramesLen.current]);
+ setCurrentIndex(lastFramesLen.current);
+ }
+ lastFramesLen.current = frames.length;
+ }, [isLoading, frames]);
+
+ return {
+ currentFrame,
+ setCurrentFrame,
+ };
+};
diff --git a/pipes/rewind/src/lib/hooks/use-timeline-data.tsx b/pipes/rewind/src/lib/hooks/use-timeline-data.tsx
new file mode 100644
index 000000000..4ab609e7f
--- /dev/null
+++ b/pipes/rewind/src/lib/hooks/use-timeline-data.tsx
@@ -0,0 +1,54 @@
+import { DeviceFrameResponse, StreamTimeSeriesResponse } from "@/app/page";
+import { useTimelineStore } from "./use-timeline-store";
+import { useEffect } from "react";
+
+export function useTimelineData(
+ currentDate: Date,
+ setCurFrame: (frame: StreamTimeSeriesResponse) => void,
+) {
+ const {
+ frames,
+ isLoading,
+ error,
+ message,
+ connectWebSocket,
+ fetchTimeRange,
+ fetchNextDayData,
+ websocket,
+ } = useTimelineStore();
+
+ useEffect(() => {
+ // First establish WebSocket connection
+ connectWebSocket();
+ }, []); // Only connect once when component mounts
+
+ useEffect(() => {
+ // Only fetch data when WebSocket is connected
+ if (websocket && websocket.readyState === WebSocket.OPEN) {
+ const startTime = new Date(currentDate);
+ startTime.setHours(0, 0, 0, 0);
+
+ const endTime = new Date(currentDate);
+ if (endTime.getDate() === new Date().getDate()) {
+ endTime.setMinutes(endTime.getMinutes() - 5);
+ } else {
+ endTime.setHours(23, 59, 59, 999);
+ }
+
+ fetchTimeRange(startTime, endTime);
+
+ // Set initial frame if available
+ if (frames.length > 0) {
+ setCurFrame(frames[0]);
+ }
+ }
+ }, [websocket?.readyState]); // Depend on WebSocket connection state
+
+ return {
+ frames,
+ isLoading,
+ error,
+ message,
+ fetchNextDayData,
+ };
+}
diff --git a/pipes/rewind/src/lib/hooks/use-timeline-store.tsx b/pipes/rewind/src/lib/hooks/use-timeline-store.tsx
new file mode 100644
index 000000000..6f0a3c217
--- /dev/null
+++ b/pipes/rewind/src/lib/hooks/use-timeline-store.tsx
@@ -0,0 +1,234 @@
+import { create } from "zustand";
+import { StreamTimeSeriesResponse } from "@/app/page";
+import { hasFramesForDate } from "../actions/has-frames-date";
+import { subDays } from "date-fns";
+
+interface TimelineState {
+ frames: StreamTimeSeriesResponse[];
+ isLoading: boolean;
+ error: string | null;
+ message: string | null;
+ currentDate: Date;
+ websocket: WebSocket | null;
+ sentRequests: Set<string>;
+
+ // Actions
+ setFrames: (frames: StreamTimeSeriesResponse[]) => void;
+ setIsLoading: (isLoading: boolean) => void;
+ setError: (error: string | null) => void;
+ setMessage: (message: string | null) => void;
+ setCurrentDate: (date: Date) => void;
+ connectWebSocket: () => void;
+ fetchTimeRange: (startTime: Date, endTime: Date) => void;
+ fetchNextDayData: (date: Date) => void;
+ hasDateBeenFetched: (date: Date) => boolean;
+}
+
+export const useTimelineStore = create<TimelineState>((set, get) => ({
+ frames: [],
+ isLoading: true,
+ error: null,
+ message: null,
+ currentDate: new Date(),
+ websocket: null,
+ sentRequests: new Set<string>(),
+
+ setFrames: (frames) => set({ frames }),
+ setIsLoading: (isLoading) => set({ isLoading }),
+ setError: (error) => set({ error }),
+ setMessage: (message) => set({ message }),
+ setCurrentDate: (date) => set({ currentDate: date }),
+
+ hasDateBeenFetched: (date: Date) => {
+ const { sentRequests } = get();
+ const dateKey = `${date.getDate()}-${date.getMonth()}-${date.getFullYear()}`;
+ return sentRequests.has(dateKey);
+ },
+ connectWebSocket: () => {
+ const ws = new WebSocket("ws://localhost:3030/stream/frames");
+
+ ws.onopen = () => {
+ set({ websocket: ws, error: null, message: null, isLoading: true });
+ console.log("WebSocket connection established");
+ };
+
+ ws.onmessage = (event) => {
+ try {
+ const data = JSON.parse(event.data);
+
+ // Handle keep-alive messages
+ if (data === "keep-alive-text") {
+ set((state) => ({
+ error: null,
+ isLoading: false,
+ message:
+ state.message === "please wait..."
+ ? state.message
+ : "please wait...",
+ }));
+ return;
+ }
+
+ // Handle error messages
+ if (data.error) {
+ set({ error: data.error, isLoading: false });
+ return;
+ }
+
+ // Handle batched frames
+ if (Array.isArray(data)) {
+ set((state) => {
+ const newFrames = [...state.frames];
+ const uniqueFrames = new Map();
+
+ // First, add existing frames to the map
+ newFrames.forEach((frame) => {
+ uniqueFrames.set(frame.timestamp, frame);
+ });
+
+ // Add new frames to the map (this automatically handles duplicates)
+ data.forEach((frame) => {
+ uniqueFrames.set(frame.timestamp, frame);
+ });
+
+ // Convert map back to array and sort by timestamp
+ const sortedFrames = Array.from(uniqueFrames.values()).sort(
+ (a, b) =>
+ new Date(b.timestamp).getTime() -
+ new Date(a.timestamp).getTime(),
+ );
+
+ return {
+ frames: sortedFrames,
+ isLoading: false,
+ message: null,
+ error: null,
+ };
+ });
+ return;
+ }
+
+ // Handle single frame (legacy support)
+ if (data.timestamp && data.devices) {
+ set((state) => {
+ const timestamp = new Date(data.timestamp).getTime();
+
+ // Check for duplicate
+ if (
+ state.frames.some(
+ (f) => new Date(f.timestamp).getTime() === timestamp,
+ )
+ ) {
+ return state;
+ }
+
+ // Use binary search to find insertion point
+ const newFrames = [...state.frames];
+ let left = 0;
+ let right = newFrames.length;
+
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2);
+ const midTimestamp = new Date(newFrames[mid].timestamp).getTime();
+ if (midTimestamp < timestamp) {
+ right = mid;
+ } else {
+ left = mid + 1;
+ }
+ }
+
+ newFrames.splice(left, 0, data);
+ return {
+ frames: newFrames,
+ isLoading: false,
+ message: null,
+ error: null,
+ };
+ });
+ }
+ } catch (error) {
+ console.error("Failed to parse frame data:", error);
+ set({
+ error: "Failed to parse server response",
+ isLoading: false,
+ });
+ }
+ };
+
+ ws.onerror = (error) => {
+ console.error("WebSocket error:", error);
+ set({ error: "Connection error occurred", isLoading: false });
+ };
+
+ ws.onclose = () => {
+ set({ message: "Connection closed", isLoading: false });
+ // Attempt to reconnect after a delay
+ setTimeout(() => get().connectWebSocket(), 5000);
+ };
+ },
+
+ fetchTimeRange: async (startTime: Date, endTime: Date) => {
+ const { websocket, sentRequests } = get();
+ const requestKey = `${startTime.getDate()}-${startTime.getMonth()}-${startTime.getFullYear()}`;
+
+ if (sentRequests.has(requestKey)) {
+ console.log("Request already sent, skipping...");
+ return;
+ }
+
+ if (websocket && websocket.readyState === WebSocket.OPEN) {
+ console.log("sending");
+ websocket.send(
+ JSON.stringify({
+ start_time: startTime.toISOString(),
+ end_time: endTime.toISOString(),
+ order: "descending",
+ }),
+ );
+
+ set((state) => ({
+ sentRequests: new Set(state.sentRequests).add(requestKey),
+ }));
+ }
+ },
+
+ fetchNextDayData: async (date: Date) => {
+ const dateFramesLen = await hasFramesForDate(date);
+
+ if (typeof dateFramesLen === "object" && dateFramesLen.error) {
+ return;
+ }
+
+ if (!dateFramesLen) {
+ date = subDays(date, 1);
+ }
+
+ const nextDay = new Date(date);
+ nextDay.setDate(nextDay.getDate());
+ nextDay.setHours(0, 0, 0, 0);
+
+ const endTime = new Date(nextDay);
+ endTime.setHours(23, 59, 59, 999);
+
+ const { websocket, sentRequests } = get();
+ const requestKey = `${nextDay.getDate()}-${nextDay.getMonth()}-${nextDay.getFullYear()}`;
+
+ if (sentRequests.has(requestKey)) {
+ console.log("Request already sent, skipping...");
+ return;
+ }
+
+ if (websocket && websocket.readyState === WebSocket.OPEN) {
+ websocket.send(
+ JSON.stringify({
+ start_time: nextDay.toISOString(),
+ end_time: endTime.toISOString(),
+ order: "descending",
+ }),
+ );
+ set((state) => ({
+ sentRequests: new Set(state.sentRequests).add(requestKey),
+ }));
+ }
+ },
+}));
diff --git a/pipes/rewind/src/lib/utils.ts b/pipes/rewind/src/lib/utils.ts
index 847c458cf..1dcf56583 100644
--- a/pipes/rewind/src/lib/utils.ts
+++ b/pipes/rewind/src/lib/utils.ts
@@ -4,57 +4,57 @@ import { twMerge } from "tailwind-merge";
import levenshtein from "js-levenshtein";
export function cn(...inputs: ClassValue[]) {
- return twMerge(clsx(inputs));
+ return twMerge(clsx(inputs));
}
export const removeDuplicateSelections = (
- results: ContentItem[],
- selectedResults: Set<number>,
- similarityThreshold: number = 0.9
+ results: ContentItem[],
+ selectedResults: Set<number>,
+ similarityThreshold: number = 0.9,
): Set<number> => {
- const newSelectedResults = new Set<number>();
- const seenContents: string[] = [];
-
- const getSimilarity = (str1: string, str2: string): number => {
- const maxLength = Math.max(str1.length, str2.length);
- const distance = levenshtein(str1, str2);
- return 1 - distance / maxLength;
- };
-
- const isDuplicate = (content: string): boolean => {
- return seenContents.some(
- (seenContent) =>
- getSimilarity(content, seenContent) >= similarityThreshold
- );
- };
-
- Array.from(selectedResults).forEach((index) => {
- const item = results[index];
- if (!item || !item.type) return;
-
- let content = "";
- if (item.type === "OCR") content = item.content.text;
- else if (item.type === "Audio") content = item.content.transcription;
- else if (item.type === "UI") content = item.content.text;
-
- if (!isDuplicate(content)) {
- seenContents.push(content);
- newSelectedResults.add(index);
- }
- });
-
- return newSelectedResults;
+ const newSelectedResults = new Set<number>();
+ const seenContents: string[] = [];
+
+ const getSimilarity = (str1: string, str2: string): number => {
+ const maxLength = Math.max(str1.length, str2.length);
+ const distance = levenshtein(str1, str2);
+ return 1 - distance / maxLength;
+ };
+
+ const isDuplicate = (content: string): boolean => {
+ return seenContents.some(
+ (seenContent) =>
+ getSimilarity(content, seenContent) >= similarityThreshold,
+ );
+ };
+
+ Array.from(selectedResults).forEach((index) => {
+ const item = results[index];
+ if (!item || !item.type) return;
+
+ let content = "";
+ if (item.type === "OCR") content = item.content.text;
+ else if (item.type === "Audio") content = item.content.transcription;
+ else if (item.type === "UI") content = item.content.text;
+
+ if (!isDuplicate(content)) {
+ seenContents.push(content);
+ newSelectedResults.add(index);
+ }
+ });
+
+ return newSelectedResults;
};
export function stringToColor(str: string): string {
- let hash = 0;
- for (let i = 0; i < str.length; i++) {
- hash = str.charCodeAt(i) + ((hash << 5) - hash);
- }
- let color = "#";
- for (let i = 0; i < 3; i++) {
- const value = (hash >> (i * 8)) & 0xff;
- color += ("00" + value.toString(16)).substr(-2);
- }
- return color;
+ let hash = 0;
+ for (let i = 0; i < str.length; i++) {
+ hash = str.charCodeAt(i) + ((hash << 5) - hash);
+ }
+ let color = "#";
+ for (let i = 0; i < 3; i++) {
+ const value = (hash >> (i * 8)) & 0xff;
+ color += ("00" + value.toString(16)).substr(-2);
+ }
+ return color;
}
diff --git a/screenpipe-app-tauri/src-tauri/src/icons.rs b/screenpipe-app-tauri/src-tauri/src/icons.rs
index d5f0164af..06d8708e5 100644
--- a/screenpipe-app-tauri/src-tauri/src/icons.rs
+++ b/screenpipe-app-tauri/src-tauri/src/icons.rs
@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct AppIcon {
- pub base64: String,
+ pub data: Vec<u8>,
pub path: Option<String>,
}
@@ -11,7 +11,6 @@ pub async fn get_app_icon(
app_name: &str,
app_path: Option<String>,
) -> Result<Option<AppIcon>, String> {
- use base64::{engine::general_purpose::STANDARD, Engine};
use cocoa::base::{id, nil};
use cocoa::foundation::{NSAutoreleasePool, NSData, NSString};
use objc::{class, msg_send, sel, sel_impl};
@@ -48,16 +47,14 @@ pub async fn get_app_icon(
let tiff_data: id = msg_send![icon, TIFFRepresentation];
let image_rep: id = msg_send![class!(NSBitmapImageRep), imageRepWithData: tiff_data];
- let png_data: id = msg_send![image_rep, representationUsingType:4 properties:nil];
+ let jpeg_data: id = msg_send![image_rep, representationUsingType:3 properties:nil]; // Type 3 is JPEG
- let length = NSData::length(png_data);
- let bytes = NSData::bytes(png_data);
- let data = std::slice::from_raw_parts(bytes as *const u8, length as usize);
-
- let base64 = STANDARD.encode(data);
+ let length = NSData::length(jpeg_data);
+ let bytes = NSData::bytes(jpeg_data);
+ let data = std::slice::from_raw_parts(bytes as *const u8, length as usize).to_vec();
Ok(Some(AppIcon {
- base64,
+ data,
path: Some(path),
}))
})();
@@ -85,7 +82,7 @@ pub async fn get_app_icon(
app_name: &str,
app_path: Option<String>,
) -> Result<Option<AppIcon>, String> {
- use windows_icons::get_icon_base64_by_path;
+ use windows_icons::get_icon_image_by_path;
async fn find_exe_path(app_name: &str) -> Option<String> {
if let Some(path) = get_exe_by_reg_key(app_name) {
@@ -107,12 +104,12 @@ pub async fn get_app_icon(
.ok_or_else(|| "app_path is None and could not find executable path".to_string())?,
};
- let base64 = get_icon_base64_by_path(&path)
+ let data = get_icon_image_by_path(&path)
.await
.map_err(|e| e.to_string())?;
Ok(Some(AppIcon {
- base64,
+ data,
path: Some(path),
}))
}
@@ -310,7 +307,6 @@ pub async fn get_app_icon(
app_name: &str,
app_path: Option<String>,
) -> Result<Option<AppIcon>, String> {
- use base64::{engine::general_purpose::STANDARD, Engine};
use gtk::prelude::IconThemeExt;
use std::fs;
@@ -331,11 +327,10 @@ pub async fn get_app_icon(
None => find_icon_path(app_name).ok_or_else(|| "could not find icon path".to_string())?,
};
- let icon_data = fs::read(&path).map_err(|e| e.to_string())?;
- let base64 = STANDARD.encode(&icon_data);
+ let data = fs::read(&path).map_err(|e| e.to_string())?;
Ok(Some(AppIcon {
- base64,
+ data,
path: Some(path),
}))
}
diff --git a/screenpipe-app-tauri/src-tauri/src/server.rs b/screenpipe-app-tauri/src-tauri/src/server.rs
index 5ac818728..ad7e8d80b 100644
--- a/screenpipe-app-tauri/src-tauri/src/server.rs
+++ b/screenpipe-app-tauri/src-tauri/src/server.rs
@@ -1,12 +1,14 @@
-use crate::{get_store, get_base_dir, icons::AppIcon};
+use crate::{get_base_dir, get_store, icons::AppIcon};
+use axum::body::Bytes;
use axum::response::sse::{Event, Sse};
+use axum::response::IntoResponse;
use axum::{
extract::{Query, State},
http::{Method, StatusCode},
Json, Router,
};
use futures::stream::Stream;
-use http::header::HeaderValue;
+use http::header::{HeaderValue, CONTENT_TYPE};
use notify::RecursiveMode;
use notify::Watcher;
use serde::{Deserialize, Serialize};
@@ -117,8 +119,8 @@ pub async fn run_server(app_handle: tauri::AppHandle, port: u16) {
let (settings_tx, _) = broadcast::channel(100);
let settings_tx_clone = settings_tx.clone();
let app_handle_clone = app_handle.clone();
- let base_dir =
- get_base_dir(&app_handle, None).expect("Failed to ensure local data directory");
+
+ let base_dir = get_base_dir(&app_handle, None).expect("Failed to ensure local data directory");
let store_path = base_dir.join("store.bin");
let mut watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
@@ -285,13 +287,23 @@ async fn handle_auth(
async fn get_app_icon_handler(
State(_): State<ServerState>,
Query(app_name): Query<AppIconQuery>,
-) -> Result<Json<Option<AppIcon>>, (StatusCode, String)> {
+) -> Result<impl IntoResponse, (StatusCode, String)> {
info!("received app icon request: {:?}", app_name);
#[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
{
match crate::icons::get_app_icon(&app_name.name, app_name.path).await {
- Ok(icon) => Ok(Json(icon)),
+ Ok(Some(icon)) => {
+ let headers = [
+ (CONTENT_TYPE, HeaderValue::from_static("image/jpeg")),
+ (
+ http::header::CACHE_CONTROL,
+ HeaderValue::from_static("public, max-age=604800"),
+ ),
+ ];
+ Ok((headers, Bytes::from(icon.data)))
+ }
+ Ok(None) => Err((StatusCode::NOT_FOUND, "Icon not found".to_string())),
Err(e) => {
error!("failed to get app icon: {}", e);
Err((
@@ -356,7 +368,6 @@ pub fn spawn_server(app_handle: tauri::AppHandle, port: u16) -> mpsc::Sender<()>
/*
-
curl -X POST http://localhost:11435/notify \
-H "Content-Type: application/json" \
-d '{"title": "Test Notification", "body": "This is a test notification body"}'
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.toml
index d4f3b2f34..fac91bac4 100644
--- a/screenpipe-server/Cargo.toml
+++ b/screenpipe-server/Cargo.toml
@@ -49,7 +49,7 @@ thiserror = "1"
sentry = { workspace = true }
# Server
-axum = "0.7.5"
+axum = { version = "0.7.5", features = ["ws"]}
axum-macros = "0.5.0"
async-stream = "0.3"
tokio = { version = "1.15", features = ["full", "tracing"] }
@@ -123,6 +123,8 @@ walkdir = "2.3.4"
regex = "1.10.0"
+lru = "0.13.0"
+tokio-util = { version = "0.7", features = ["io"] }
[dev-dependencies]
env_logger = "0.10"
tempfile = "3.3.0"
diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rs
index 71584527a..c4d2df8a2 100644
--- a/screenpipe-server/src/db.rs
+++ b/screenpipe-server/src/db.rs
@@ -1366,43 +1366,162 @@ impl DatabaseManager {
// ! just merging
// ! the offset is not quite right but we try to index around frames which is the central human experience and most important sense
// ! there should be a way to properly sync audio and video indexes
+ //pub async fn find_video_chunks(
+ // &self,
+ // start: DateTime<Utc>,
+ // end: DateTime<Utc>,
+ //) -> Result<TimeSeriesChunk, SqlxError> {
+ // // First get all frames in time range with their OCR data
+ // let frames_query = r#"
+ // SELECT
+ // f.id,
+ // f.timestamp,
+ // f.offset_index,
+ // ot.text,
+ // ot.app_name,
+ // ot.window_name,
+ // vc.device_name as screen_device,
+ // vc.file_path as video_path
+ // FROM frames f
+ // JOIN video_chunks vc ON f.video_chunk_id = vc.id
+ // LEFT JOIN ocr_text ot ON f.id = ot.frame_id
+ // WHERE f.timestamp >= ?1 AND f.timestamp <= ?2
+ // ORDER BY f.timestamp DESC, f.offset_index DESC
+ // "#;
+
+ // // Then get audio data that overlaps with these frames
+ // let audio_query = r#"
+ // SELECT
+ // at.timestamp,
+ // at.transcription,
+ // at.device as audio_device,
+ // at.is_input_device,
+ // ac.file_path as audio_path
+ // FROM audio_transcriptions at
+ // JOIN audio_chunks ac ON at.audio_chunk_id = ac.id
+ // WHERE at.timestamp >= ?1 AND at.timestamp <= ?2
+ // ORDER BY at.timestamp DESC
+ // "#;
+
+ // // Execute both queries
+ // let (frame_rows, audio_rows) = tokio::try_join!(
+ // sqlx::query(frames_query)
+ // .bind(start)
+ // .bind(end)
+ // .fetch_all(&self.pool),
+ // sqlx::query(audio_query)
+ // .bind(start)
+ // .bind(end)
+ // .fetch_all(&self.pool)
+ // )?;
+
+ // // Process into structured data
+ // let mut frames_map: BTreeMap<(DateTime<Utc>, i64), FrameData> = BTreeMap::new();
+
+ // // Process frame/OCR data
+ // for row in frame_rows {
+ // let timestamp: DateTime<Utc> = row.get("timestamp");
+ // let offset_index: i64 = row.get("offset_index");
+ // let key = (timestamp, offset_index);
+
+ // let frame_data = frames_map.entry(key).or_insert_with(|| FrameData {
+ // frame_id: row.get("id"),
+ // timestamp,
+ // offset_index,
+ // ocr_entries: Vec::new(),
+ // audio_entries: Vec::new(),
+ // });
+
+ // if let Ok(text) = row.try_get::<String, _>("text") {
+ // frame_data.ocr_entries.push(OCREntry {
+ // text,
+ // app_name: row.get("app_name"),
+ // window_name: row.get("window_name"),
+ // device_name: row.get("screen_device"),
+ // video_file_path: row.get("video_path"),
+ // });
+ // }
+ // }
+
+ // // Process audio data
+ // 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() {
+ // 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"),
+ // duration_secs: 0.0, // TODO
+ // });
+ // }
+ // }
+ // }
+
+ // Ok(TimeSeriesChunk {
+ // frames: frames_map.into_values().rev().collect(),
+ // start_time: start,
+ // end_time: end,
+ // })
+ //}
+
pub async fn find_video_chunks(
&self,
start: DateTime<Utc>,
end: DateTime<Utc>,
) -> Result<TimeSeriesChunk, SqlxError> {
- // First get all frames in time range with their OCR data
+ // Get frames with OCR data, grouped by minute to handle multiple monitors
let frames_query = r#"
+ WITH MinuteGroups AS (
SELECT
+ f.id,
f.timestamp,
f.offset_index,
ot.text,
ot.app_name,
ot.window_name,
vc.device_name as screen_device,
- vc.file_path as video_path
+ vc.file_path as video_path,
+ strftime('%Y-%m-%d %H:%M', f.timestamp) as minute_group,
+ ROW_NUMBER() OVER (
+ PARTITION BY strftime('%Y-%m-%d %H:%M', f.timestamp), ot.app_name, vc.device_name
+ ORDER BY f.timestamp DESC
+ ) as rn
FROM frames f
JOIN video_chunks vc ON f.video_chunk_id = vc.id
LEFT JOIN ocr_text ot ON f.id = ot.frame_id
WHERE f.timestamp >= ?1 AND f.timestamp <= ?2
- ORDER BY f.timestamp DESC, f.offset_index DESC
- "#;
+ )
+ SELECT *
+ FROM MinuteGroups
+ WHERE rn = 1
+ ORDER BY timestamp DESC, offset_index DESC
+ "#;
- // Then get audio data that overlaps with these frames
+ // Get audio data with proper time windows for synchronization
let audio_query = r#"
- SELECT
- at.timestamp,
- at.transcription,
- at.device as audio_device,
- at.is_input_device,
- ac.file_path as audio_path
- FROM audio_transcriptions at
- JOIN audio_chunks ac ON at.audio_chunk_id = ac.id
- WHERE at.timestamp >= ?1 AND at.timestamp <= ?2
- ORDER BY at.timestamp DESC
+ SELECT
+ at.timestamp,
+ at.transcription,
+ at.device as audio_device,
+ at.is_input_device,
+ ac.file_path as audio_path,
+ at.start_time,
+ at.end_time,
+ CAST((julianday(datetime(at.timestamp, '+' || at.end_time || ' seconds')) -
+ julianday(datetime(at.timestamp, '+' || at.start_time || ' seconds'))) * 86400
+ as REAL) as duration_secs
+ FROM audio_transcriptions at
+ JOIN audio_chunks ac ON at.audio_chunk_id = ac.id
+ WHERE at.timestamp >= ?1 AND at.timestamp <= ?2
+ ORDER BY at.timestamp DESC
"#;
- // Execute both queries
+ // Execute queries in parallel
let (frame_rows, audio_rows) = tokio::try_join!(
sqlx::query(frames_query)
.bind(start)
@@ -1414,16 +1533,17 @@ impl DatabaseManager {
.fetch_all(&self.pool)
)?;
- // Process into structured data
+ // Process into structured data with device-aware grouping
let mut frames_map: BTreeMap<(DateTime<Utc>, i64), FrameData> = BTreeMap::new();
- // Process frame/OCR data
+ // Process frame/OCR data with device awareness
for row in frame_rows {
let timestamp: DateTime<Utc> = row.get("timestamp");
let offset_index: i64 = row.get("offset_index");
let key = (timestamp, offset_index);
let frame_data = frames_map.entry(key).or_insert_with(|| FrameData {
+ frame_id: row.get("id"),
timestamp,
offset_index,
ocr_entries: Vec::new(),
@@ -1441,20 +1561,23 @@ impl DatabaseManager {
}
}
- // Process audio data
+ // 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() {
+ 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 {
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"),
- duration_secs: 0.0, // TODO
+ duration_secs: row.get("duration_secs"),
});
}
}
@@ -1921,7 +2044,7 @@ impl DatabaseManager {
let sql = r#"
WITH embedding_matches AS (
- SELECT
+ SELECT
frame_id,
vec_distance_cosine(embedding, vec_f32(?1)) as similarity
FROM ocr_text_embeddings
diff --git a/screenpipe-server/src/db_types.rs b/screenpipe-server/src/db_types.rs
index 6c5352e8b..8a8d066cb 100644
--- a/screenpipe-server/src/db_types.rs
+++ b/screenpipe-server/src/db_types.rs
@@ -136,6 +136,7 @@ pub struct UiContent {
#[derive(Debug, Clone)]
pub struct FrameData {
+ pub frame_id: i64,
pub timestamp: DateTime<Utc>,
pub offset_index: i64,
pub ocr_entries: Vec<OCREntry>,
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 72a88115e..a9a191baa 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -1,35 +1,45 @@
use axum::{
- extract::{Json, Path, Query, State},
+ body::Body,
+ extract::{
+ ws::{Message, WebSocket},
+ Json, Path, Query, State, WebSocketUpgrade,
+ },
http::StatusCode,
- response::{sse::Event, IntoResponse, Json as JsonResponse, Sse},
+ response::{sse::Event, IntoResponse, Json as JsonResponse, Response, Sse},
routing::{get, post},
serve, Router,
};
+use tokio_util::io::ReaderStream;
+
+use tokio::fs::File;
+
use futures::{
future::{try_join, try_join_all},
- Stream,
+ SinkExt, Stream, StreamExt,
};
use image::ImageFormat::{self};
use screenpipe_core::{AudioDevice, AudioDeviceType, DeviceControl, DeviceManager};
use crate::{
- db_types::{ContentType, SearchResult, Speaker, TagContentType},
+ core::DeviceManager,
+ db_types::{ContentType, FrameData, SearchResult, Speaker, TagContentType},
pipe_manager::PipeManager,
video::{finish_ffmpeg_process, start_ffmpeg_process, write_frame_to_ffmpeg, MAX_FPS},
- video_cache::{FrameCache, TimeSeriesFrame},
+ video_cache::{AudioEntry, DeviceFrame, FrameCache, FrameMetadata, TimeSeriesFrame},
video_utils::{
- merge_videos, validate_media, MergeVideosRequest, MergeVideosResponse, ValidateMediaParams,
+ extract_frame_from_video, merge_videos, validate_media, MergeVideosRequest,
+ MergeVideosResponse, ValidateMediaParams,
},
DatabaseManager,
};
use crate::{plugin::ApiPluginLayer, video_utils::extract_frame};
-use base64::prelude::*;
use chrono::{DateTime, Utc};
use log::{debug, error, info};
use screenpipe_audio::{
default_input_device, default_output_device, list_audio_devices,
realtime::RealtimeTranscriptionEvent,
};
+
use screenpipe_vision::OcrEngine;
use screenpipe_vision::{core::RealtimeVisionEvent, monitor::list_monitors};
use serde::{Deserialize, Deserializer, Serialize};
@@ -37,12 +47,23 @@ use serde_json::{json, Value};
use std::{
convert::Infallible,
net::SocketAddr,
+ num::NonZeroUsize,
path::PathBuf,
- sync::{atomic::Ordering, Arc},
- time::Duration,
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+ },
+ time::{Duration, Instant},
+};
+
+use lru::LruCache;
+
+use tokio::{
+ net::TcpListener,
+ sync::{broadcast, mpsc, Mutex},
+ time::timeout,
};
-use tokio::net::TcpListener;
use tower_http::{cors::Any, trace::TraceLayer};
use tower_http::{cors::CorsLayer, trace::DefaultMakeSpan};
@@ -66,6 +87,7 @@ pub struct AppState {
pub audio_disabled: bool,
pub ui_monitoring_enabled: bool,
pub frame_cache: Option<Arc<FrameCache>>,
+ pub frame_image_cache: Option<Arc<Mutex<LruCache<i64, (String, Instant)>>>>,
pub realtime_transcription_enabled: bool,
pub realtime_transcription_sender:
Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,
@@ -906,6 +928,13 @@ impl Server {
} else {
None
},
+ frame_image_cache: if enable_frame_cache {
+ Some(Arc::new(Mutex::new(LruCache::new(
+ NonZeroUsize::new(100).unwrap(),
+ ))))
+ } else {
+ None
+ },
realtime_transcription_enabled: self.realtime_transcription_enabled,
realtime_transcription_sender: Arc::new(self.realtime_transcription_sender),
realtime_vision_sender: self.realtime_vision_sender,
@@ -1322,18 +1351,26 @@ struct InputControlResponse {
#[derive(Deserialize, PartialEq)]
enum Order {
+ #[serde(rename = "ascending")]
Ascending,
+ #[serde(rename = "descending")]
Descending,
}
+impl Order {
+ fn default() -> Self {
+ Order::Descending
+ }
+}
+
// Add this new struct
#[derive(Deserialize)]
pub struct StreamFramesRequest {
start_time: DateTime<Utc>,
end_time: DateTime<Utc>,
- // #[serde(rename = "order")]
- // #[serde(default = "descending")]
- // order: Order,
+ #[serde(rename = "order")]
+ #[serde(default = "Order::default")]
+ order: Order,
}
#[derive(Debug, Serialize)]
@@ -1345,7 +1382,8 @@ pub struct StreamTimeSeriesResponse {
#[derive(Debug, Serialize)]
pub struct DeviceFrameResponse {
pub device_id: String,
- pub frame: String, // base64 encoded image
+ // pub frame: String, // base64 encoded image
+ pub frame_id: i64,
pub metadata: DeviceMetadata,
pub audio: Vec<AudioData>,
}
@@ -1378,7 +1416,8 @@ impl From<TimeSeriesFrame> for StreamTimeSeriesResponse {
.map(|device_frame| {
DeviceFrameResponse {
device_id: device_frame.device_id,
- frame: BASE64_STANDARD.encode(&device_frame.image_data),
+ // frame: BASE64_STANDARD.encode(&device_frame.image_data),
+ frame_id: device_frame.frame_id,
metadata: DeviceMetadata {
file_path: device_frame.metadata.file_path,
app_name: device_frame.metadata.app_name,
@@ -1981,6 +2020,7 @@ pub fn create_router() -> Router<Arc<AppState>> {
.route("/audio/stop", post(stop_audio_device))
.route("/sse/vision", get(sse_vision_handler))
.route("/semantic-search", get(semantic_search_handler))
+ .route("/frames/:frame_id", get(get_frame_data))
.route("/vision/start", post(start_vision_device))
.route("/vision/stop", post(stop_vision_device))
.layer(cors);
@@ -1993,90 +2033,306 @@ pub fn create_router() -> Router<Arc<AppState>> {
router
}
-// Add the new handler
-async fn stream_frames_handler(
- Query(request): Query<StreamFramesRequest>,
+pub async fn get_frame_data(
State(state): State<Arc<AppState>>,
-) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
- info!(
- "streaming frames from {} to {}",
- request.start_time, request.end_time
- );
-
- let (frame_tx, mut frame_rx) = tokio::sync::mpsc::channel(100);
-
- // Create a stream that will be used for both success and error cases
- let stream = async_stream::stream! {
- // Early validation of frame cache
- let cache = match state.frame_cache.as_ref() {
- Some(cache) => cache.clone(),
- None => {
- // error!("frame cache not initialized");
- yield Ok(Event::default().data("{\"error\": \"frame cache not initialized\"}"));
- return;
+ Path(frame_id): Path<i64>,
+) -> Result<impl IntoResponse, (StatusCode, JsonResponse<Value>)> {
+ let start_time = Instant::now();
+
+ match timeout(Duration::from_secs(5), async {
+ // Try to get frame from cache if enabled
+ if let Some(cache) = &state.frame_image_cache {
+ let cache_result = cache.try_lock();
+ match cache_result {
+ Ok(mut cache) => {
+ if let Some((file_path, timestamp)) = cache.get(&frame_id) {
+ if timestamp.elapsed() < Duration::from_secs(300) {
+ debug!(
+ "Cache hit for frame_id: {}. Retrieved in {:?}",
+ frame_id,
+ start_time.elapsed()
+ );
+ return serve_file(file_path).await;
+ }
+ cache.pop(&frame_id);
+ }
+ }
+ Err(_) => {
+ debug!("Cache lock contention for frame_id: {}", frame_id);
+ }
}
- };
-
- // Calculate duration in minutes between start and end time
- let duration_minutes = (request.end_time - request.start_time).num_minutes().max(1);
-
- // Calculate center timestamp
- let center_timestamp = request.start_time + (request.end_time - request.start_time) / 2;
-
- // Use a cancellation token to handle client disconnection
- let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel();
-
- // Spawn frame extraction task using get_frames
- tokio::spawn({
- let frame_tx = frame_tx.clone();
- async move {
- tokio::select! {
- result = cache.get_frames(center_timestamp, duration_minutes, frame_tx.clone(), true) => {
- if let Err(e) = result {
- error!("frame extraction failed: {}", e);
- // Send error to client
- let _ = frame_tx.send(TimeSeriesFrame {
- timestamp: Utc::now(),
- frame_data: vec![],
- error: Some(format!("frame extraction failed: {}", e)),
- }).await;
+ }
+
+ // If not in cache or cache disabled, get from database
+ match state.db.get_frame(frame_id).await {
+ Ok(Some((file_path, offset_index))) => {
+ match extract_frame_from_video(&file_path, offset_index).await {
+ Ok(frame_path) => {
+ // Store in cache if enabled and we can get the lock
+ if let Some(cache) = &state.frame_image_cache {
+ if let Ok(mut cache) = cache.try_lock() {
+ cache.put(frame_id, (frame_path.clone(), Instant::now()));
+ }
}
+
+ debug!("Frame {} extracted in {:?}", frame_id, start_time.elapsed());
+ serve_file(&frame_path).await
}
- _ = cancel_rx => {
- debug!("client disconnected, stopping frame stream");
+ Err(e) => {
+ error!("Failed to extract frame {}: {}", frame_id, e);
+ Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({
+ "error": format!("Failed to extract frame: {}", e),
+ "frame_id": frame_id,
+ "file_path": file_path
+ })),
+ ))
}
}
}
- });
+ Ok(None) => Err((
+ StatusCode::NOT_FOUND,
+ JsonResponse(json!({
+ "error": "Frame not found",
+ "frame_id": frame_id
+ })),
+ )),
+ Err(e) => Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({
+ "error": format!("Database error: {}", e),
+ "frame_id": frame_id
+ })),
+ )),
+ }
+ })
+ .await
+ {
+ Ok(result) => result,
+ Err(_) => {
+ error!("Request timeout for frame_id: {}", frame_id);
+ Err((
+ StatusCode::REQUEST_TIMEOUT,
+ JsonResponse(json!({
+ "error": "Request timed out",
+ "frame_id": frame_id
+ })),
+ ))
+ }
+ }
+}
- let _cancel_guard = scopeguard::guard(cancel_tx, |tx| {
- let _ = tx.send(()); // Signal cancellation when stream is dropped
- });
+async fn serve_file(path: &str) -> Result<Response, (StatusCode, JsonResponse<Value>)> {
+ match File::open(path).await {
+ Ok(file) => {
+ let stream = ReaderStream::new(file);
+ let body = Body::from_stream(stream);
+
+ let response = Response::builder()
+ .header("content-type", "image/jpeg")
+ .header("cache-control", "public, max-age=604800") // Cache for 7 days
+ .body(body)
+ .map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": format!("Failed to create response: {}", e)})),
+ )
+ })?;
+
+ Ok(response)
+ }
+ Err(e) => Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": format!("Failed to open file: {}", e)})),
+ )),
+ }
+}
+
+// Add these new functions before stream_frames_handler
+async fn fetch_and_process_frames(
+ db: Arc<DatabaseManager>,
+ start_time: DateTime<Utc>,
+ end_time: DateTime<Utc>,
+ frame_tx: mpsc::Sender<TimeSeriesFrame>,
+ is_descending: bool,
+) -> Result<(), anyhow::Error> {
+ let mut chunks = db.find_video_chunks(start_time, end_time).await?;
+
+ // Sort chunks based on order
+ if is_descending {
+ chunks
+ .frames
+ .sort_by_key(|a| std::cmp::Reverse((a.timestamp, a.offset_index)));
+ } else {
+ chunks.frames.sort_by_key(|a| (a.timestamp, a.offset_index));
+ }
- while let Some(timeseries_frame) = frame_rx.recv().await {
- // Handle potential error in the frame
- if let Some(error) = timeseries_frame.error {
- yield Ok(Event::default().data(format!("{{\"error\": \"{}\"}}", error)));
- break; // Stop streaming on error
+ for chunk in chunks.frames {
+ let frame = create_time_series_frame(chunk);
+ frame_tx.send(frame).await?;
+ }
+
+ Ok(())
+}
+
+fn create_time_series_frame(chunk: FrameData) -> TimeSeriesFrame {
+ TimeSeriesFrame {
+ timestamp: chunk.timestamp,
+ frame_data: chunk
+ .ocr_entries
+ .into_iter()
+ .map(|device_data| DeviceFrame {
+ device_id: device_data.device_name,
+ frame_id: chunk.frame_id,
+ image_data: vec![], // Empty since we don't need image data
+ metadata: FrameMetadata {
+ file_path: device_data.video_file_path,
+ app_name: device_data.app_name,
+ window_name: device_data.window_name,
+ transcription: chunk
+ .audio_entries
+ .iter()
+ .map(|a| a.transcription.clone())
+ .collect::<Vec<_>>()
+ .join(" "),
+ ocr_text: device_data.text,
+ },
+ 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(),
+ })
+ .collect(),
+ error: None,
+ }
+}
+
+async fn handle_stream_frames_socket(socket: WebSocket, state: Arc<AppState>) {
+ let (mut sender, mut receiver) = socket.split();
+ let (frame_tx, mut frame_rx) = tokio::sync::mpsc::channel(100);
+ let db = state.db.clone();
+
+ // Create a buffer for batching frames
+ let mut frame_buffer = Vec::with_capacity(50);
+ let mut buffer_timer = tokio::time::interval(Duration::from_millis(100));
+
+ // Handle incoming messages for time range requests
+ let receive_handle = tokio::spawn(async move {
+ while let Some(Ok(msg)) = receiver.next().await {
+ if let Message::Text(text) = msg {
+ match serde_json::from_str::<StreamFramesRequest>(&text) {
+ Ok(request) => {
+ debug!(
+ "streaming frames from {} to {}",
+ request.start_time, request.end_time
+ );
+
+ let frame_tx = frame_tx.clone();
+ let db = db.clone();
+
+ tokio::spawn(async move {
+ if let Err(e) = fetch_and_process_frames(
+ db,
+ request.start_time,
+ request.end_time,
+ frame_tx,
+ request.order == Order::Descending,
+ )
+ .await
+ {
+ error!("frame fetching failed: {}", e);
+ }
+ });
+ }
+ Err(e) => {
+ error!("failed to parse stream request: {}", e);
+ }
+ }
}
+ }
+ });
+
+ // Send frames to the client with batching
+ let send_handle = tokio::spawn(async move {
+ loop {
+ tokio::select! {
+ // Check for new frames
+ frame = frame_rx.recv() => {
+ match frame {
+ Some(timeseries_frame) => {
+ if let Some(error) = timeseries_frame.error {
+ if let Err(e) = sender
+ .send(Message::Text(format!("{{\"error\": \"{}\"}}", error)))
+ .await
+ {
+ error!("failed to send error message: {}", e);
+ break;
+ }
+ continue;
+ }
+
+ // Add frame to buffer
+ frame_buffer.push(StreamTimeSeriesResponse::from(timeseries_frame));
- // Convert frame to response and send
- match serde_json::to_string(&StreamTimeSeriesResponse::from(timeseries_frame)) {
- Ok(json) => yield Ok(Event::default().data(json)),
- Err(e) => {
- error!("failed to serialize frame: {}", e);
- yield Ok(Event::default().data(format!("{{\"error\": \"failed to serialize frame: {}\"}}", e)));
- break;
+ // If buffer is full, send immediately
+ if frame_buffer.len() >= 50 {
+ if let Err(e) = send_batch(&mut sender, &mut frame_buffer).await {
+ error!("failed to send batch: {}", e);
+ break;
+ }
+ }
+ }
+ None => break,
+ }
+ }
+ // Timer for flushing partial batches
+ _ = buffer_timer.tick() => {
+ if !frame_buffer.is_empty() {
+ if let Err(e) = send_batch(&mut sender, &mut frame_buffer).await {
+ error!("failed to send batch: {}", e);
+ break;
+ }
+ }
}
}
}
- };
+ });
- Sse::new(stream).keep_alive(
- axum::response::sse::KeepAlive::new()
- .interval(Duration::from_secs(1))
- .text("keep-alive-text"),
- )
+ // Wait for either handle to complete
+ tokio::select! {
+ _ = receive_handle => debug!("receive handle completed"),
+ _ = send_handle => debug!("send handle completed"),
+ }
+}
+
+// Helper function to send batched frames
+async fn send_batch(
+ sender: &mut futures::stream::SplitSink<WebSocket, Message>,
+ buffer: &mut Vec<StreamTimeSeriesResponse>,
+) -> Result<(), Box<dyn std::error::Error>> {
+ if buffer.is_empty() {
+ return Ok(());
+ }
+
+ // Serialize the batch
+ let json = serde_json::to_string(&buffer)?;
+ sender.send(Message::Text(json)).await?;
+ buffer.clear();
+ Ok(())
+}
+async fn stream_frames_handler(
+ ws: WebSocketUpgrade,
+ State(state): State<Arc<AppState>>,
+) -> impl IntoResponse {
+ ws.on_upgrade(move |socket| handle_stream_frames_socket(socket, state))
}
// Add this new handler function
@@ -2116,3 +2372,221 @@ struct MergeSpeakersRequest {
speaker_to_keep_id: i64,
speaker_to_merge_id: i64,
}
+/*
+
+Curl commands for reference:
+# 1. Basic search query
+curl "http://localhost:3030/search?q=test&limit=5&offset=0" | jq
+
+# 2. Search with content type filter (OCR)
+curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=ocr" | jq
+
+# 3. Search with content type filter (Audio)
+curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=audio" | jq
+
+# 4. Search with pagination
+curl "http://localhost:3030/search?q=test&limit=10&offset=20" | jq
+
+# 6. Search with no query (should return all results)
+curl "http://localhost:3030/search?limit=5&offset=0"
+
+// list devices
+// # curl "http://localhost:3030/audio/list" | jq
+
+
+echo "Listing audio devices:"
+curl "http://localhost:3030/audio/list" | jq
+
+
+echo "Searching for content:"
+curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=all" | jq
+curl "http://localhost:3030/search?limit=5&offset=0&content_type=ocr" | jq
+
+curl "http://localhost:3030/search?q=libmp3&limit=5&offset=0&content_type=all" | jq
+
+# last 5 w frames
+curl "http://localhost:3030/search?limit=5&offset=0&content_type=all&include_frames=true&start_time=$(date -u -v-5M +%Y-%m-%dT%H:%M:%SZ)" | jq
+
+# 30 min to 25 min ago
+curl "http://localhost:3030/search?limit=5&offset=0&content_type=all&include_frames=true&start_time=$(date -u -v-30M +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-25M +%Y-%m-%dT%H:%M:%SZ)" | jq
+
+curl "http://localhost:3030/search?limit=1&offset=0&content_type=all&include_frames=true&start_time=$(date -u -v-30M +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-25M +%Y-%m-%dT%H:%M:%SZ)" | jq -r '.data[0].content.frame' | base64 --decode > /tmp/frame.png && open /tmp/frame.png
+
+# Search for content from the last 30 minutes
+curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=all&start_time=$(date -u -v-30M +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-25M +%Y-%m-%dT%H:%M:%SZ)" | jq
+
+# Search for content up to 1 hour ago
+curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=all&end_time=$(date -u -v-1H +%Y-%m-%dT%H:%M:%SZ)" | jq
+
+# Search for content between 2 hours ago and 1 hour ago
+curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=all&start_time=$(date -u -v-2H +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-1H +%Y-%m-%dT%H:%M:%SZ)" | jq
+
+# Search for OCR content from yesterday
+curl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=ocr&start_time=$(date -u -v-1d -v0H -v0M -v0S +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-1d -v23H -v59M -v59S +%Y-%m-%dT%H:%M:%SZ)" | jq
+
+# Search for audio content with a keyword from the beginning of the current month
+curl "http://localhost:3030/search?q=libmp3&limit=5&offset=0&content_type=audio&start_time=$(date -u -v1d -v0H -v0M -v0S +%Y-%m-01T%H:%M:%SZ)" | jq
+
+curl "http://localhost:3030/search?app_name=cursor"
+curl "http://localhost:3030/search?content_type=audio&min_length=20"
+
+curl "http://localhost:3030/search?q=Matt&offset=0&limit=50&start_time=$(date -u -v-2H +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-1H +%Y-%m-%dT%H:%M:%SZ)" | jq .
+
+
+curl "http://localhost:3030/search?limit=50&offset=0&content_type=all&start_time=$(date -u -v-2H +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-1H +%Y-%m-%dT%H:%M:%SZ)" | jq
+
+date -u -v-2H +%Y-%m-%dT%H:%M:%SZ
+2024-08-12T06:51:54Z
+date -u -v-1H +%Y-%m-%dT%H:%M:%SZ
+2024-08-12T07:52:17Z
+
+curl 'http://localhost:3030/search?limit=50&offset=0&content_type=all&start_time=2024-08-12T06:48:18Z&end_time=2024-08-12T07:48:34Z' | jq .
+
+
+curl "http://localhost:3030/search?q=Matt&offset=0&limit=10&start_time=2024-08-12T04:00:00Z&end_time=2024-08-12T05:00:00Z&content_type=all" | jq .
+
+curl "http://localhost:3030/search?q=Matt&offset=0&limit=10&start_time=2024-08-12T06:43:53Z&end_time=2024-08-12T08:43:53Z&content_type=all" | jq .
+
+curl 'http://localhost:3030/search?offset=0&limit=10&start_time=2024-08-12T04%3A00%3A00Z&end_time=2024-08-12T05%3A00%3A00Z&content_type=all' | jq .
+
+
+
+
+
+
+
+
+
+
+
+# First, search for Rust-related content
+curl "http://localhost:3030/search?q=debug&limit=5&offset=0&content_type=ocr"
+
+# Then, assuming you found a relevant item with id 123, tag it
+curl -X POST "http://localhost:3030/tags/vision/626" \
+ -H "Content-Type: application/json" \
+ -d '{"tags": ["debug"]}'
+
+
+
+
+# List all pipes
+curl "http://localhost:3030/pipes/list" | jq
+
+# Download a new pipe
+curl -X POST "http://localhost:3030/pipes/download" \
+ -H "Content-Type: application/json" \
+ -d '{"url": "./pipes/pipe-stream-ocr-text"}' | jq
+
+curl -X POST "http://localhost:3030/pipes/download" \
+ -H "Content-Type: application/json" \
+ -d '{"url": "./pipes/pipe-security-check"}' | jq
+
+
+curl -X POST "http://localhost:3030/pipes/download" \
+ -H "Content-Type: application/json" \
+ -d '{"url": "https://github.com/mediar-ai/screenpipe/tree/main/pipes/pipe-stream-ocr-text"}' | jq
+
+
+# Get info for a specific pipe
+curl "http://localhost:3030/pipes/info/pipe-stream-ocr-text" | jq
+
+# Run a pipe
+curl -X POST "http://localhost:3030/pipes/enable" \
+ -H "Content-Type: application/json" \
+ -d '{"pipe_id": "pipe-stream-ocr-text"}' | jq
+
+
+
+ curl -X POST "http://localhost:3030/pipes/enable" \
+ -H "Content-Type: application/json" \
+ -d '{"pipe_id": "pipe-security-check"}' | jq
+
+# Stop a pipe
+curl -X POST "http://localhost:3030/pipes/disable" \
+ -H "Content-Type: application/json" \
+ -d '{"pipe_id": "pipe-stream-ocr-text"}' | jq
+
+# Update pipe configuration
+curl -X POST "http://localhost:3030/pipes/update" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "pipe_id": "pipe-stream-ocr-text",
+ "config": {
+ "key": "value",
+ "another_key": "another_value"
+ }
+ }' | jq
+
+
+
+
+
+# Basic search with min_length and max_length
+curl "http://localhost:3030/search?q=test&limit=10&offset=0&min_length=5&max_length=50" | jq
+
+# Search for OCR content with length constraints
+curl "http://localhost:3030/search?q=code&content_type=ocr&limit=5&offset=0&min_length=20&max_length=100" | jq
+
+# Search for audio content with length constraints
+curl "http://localhost:3030/search?q=meeting&content_type=audio&limit=5&offset=0&min_length=50&max_length=200" | jq
+
+# Search with time range and length constraints
+curl "http://localhost:3030/search?q=project&limit=10&offset=0&min_length=10&max_length=100&start_time=$(date -u -v-1H +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u +%Y-%m-%dT%H:%M:%SZ)" | jq
+
+# Search with app_name and length constraints
+curl "http://localhost:3030/search?app_name=cursor&limit=5&offset=0&min_length=15&max_length=150" | jq
+
+# Search with window_name and length constraints
+curl "http://localhost:3030/search?window_name=alacritty&min_length=5&max_length=50" | jq
+
+# Search for very short content
+curl "http://localhost:3030/search?q=&limit=10&offset=0&max_length=10" | jq
+
+# Search for very long content
+curl "http://localhost:3030/search?q=&limit=10&offset=0&min_length=500" | jq
+
+
+curl "http://localhost:3030/search?limit=10&offset=0&min_length=500&content_type=audio" | jq
+
+
+# read random data and generate a clip using the merge endpoint
+
+
+# Perform the search and store the response
+
+# First, let's search for some recent video content
+SEARCH_RESPONSE1=$(curl -s "http://localhost:3030/search?q=&limit=5&offset=0&content_type=ocr&start_time=$(date -u -v-30M +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-25M +%Y-%m-%dT%H:%M:%SZ)")
+SEARCH_RESPONSE2=$(curl -s "http://localhost:3030/search?q=&limit=5&offset=0&content_type=ocr&start_time=$(date -u -v-40M +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-35M +%Y-%m-%dT%H:%M:%SZ)")
+SEARCH_RESPONSE3=$(curl -s "http://localhost:3030/search?q=&limit=5&offset=0&content_type=ocr&start_time=$(date -u -v-50M +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-45M +%Y-%m-%dT%H:%M:%SZ)")
+
+# Extract the file paths from the search results without creating JSON arrays
+VIDEO_PATHS1=$(echo "$SEARCH_RESPONSE1" | jq -r '.data[].content.file_path' | sort -u)
+VIDEO_PATHS2=$(echo "$SEARCH_RESPONSE2" | jq -r '.data[].content.file_path' | sort -u)
+VIDEO_PATHS3=$(echo "$SEARCH_RESPONSE3" | jq -r '.data[].content.file_path' | sort -u)
+
+# Merge the video paths and create a single JSON array
+MERGED_VIDEO_PATHS=$(echo "$VIDEO_PATHS1"$'\n'"$VIDEO_PATHS2"$'\n'"$VIDEO_PATHS3" | sort -u | jq -R -s -c 'split("\n") | map(select(length > 0))')
+
+# Create the JSON payload for merging videos
+MERGE_PAYLOAD=$(jq -n \
+ --argjson video_paths "$MERGED_VIDEO_PATHS" \
+ '{
+ video_paths: $video_paths
+ }')
+
+echo "Merge Payload: $MERGE_PAYLOAD"
+
+# Send the merge request and store the response
+MERGE_RESPONSE=$(curl -s -X POST "http://localhost:3030/experimental/frames/merge" \
+ -H "Content-Type: application/json" \
+ -d "$MERGE_PAYLOAD")
+
+echo "Merge Response: $MERGE_RESPONSE"
+
+# Extract the merged video path from the response
+MERGED_VIDEO_PATH=$(echo "$MERGE_RESPONSE" | jq -r '.video_path')
+
+echo "Merged Video Path: $MERGED_VIDEO_PATH"
+
+*/
diff --git a/screenpipe-server/src/video_cache.rs b/screenpipe-server/src/video_cache.rs
index 7b127c3fd..c3e9709ff 100644
--- a/screenpipe-server/src/video_cache.rs
+++ b/screenpipe-server/src/video_cache.rs
@@ -30,6 +30,7 @@ pub struct TimeSeriesFrame {
#[derive(Debug, Clone)]
pub struct DeviceFrame {
pub device_id: String,
+ pub frame_id: i64,
pub image_data: Vec<u8>,
pub metadata: FrameMetadata,
pub audio_entries: Vec<AudioEntry>,
@@ -460,6 +461,7 @@ impl FrameCache {
start_time: DateTime<Utc>,
end_time: DateTime<Utc>,
frame_tx: FrameChannel,
+ descending: bool,
) -> Result<()> {
let mut extraction_queue = HashMap::new();
let mut total_frames = 0;
@@ -471,7 +473,15 @@ impl FrameCache {
let mut chunks = self.db.find_video_chunks(start_time, end_time).await?;
// Sort by timestamp to ensure consistent ordering
- chunks.frames.sort_by_key(|a| (a.timestamp, a.offset_index));
+ if descending {
+ // For descending, sort in reverse chronological order
+ chunks
+ .frames
+ .sort_by_key(|a| std::cmp::Reverse((a.timestamp, a.offset_index)));
+ } else {
+ // For ascending, sort in chronological order (default behavior)
+ chunks.frames.sort_by_key(|a| (a.timestamp, a.offset_index));
+ }
debug!("found {} chunks to process", chunks.frames.len());
@@ -499,6 +509,7 @@ impl FrameCache {
Ok(Some((frame_data, metadata, _))) => {
debug!("cache hit for {}", cache_key);
timeseries_frame.frame_data.push(DeviceFrame {
+ frame_id: chunk.frame_id,
device_id: device_data.device_name.clone(),
image_data: frame_data,
metadata,
@@ -576,7 +587,7 @@ impl FrameCache {
let cache_clone = self.clone();
tokio::spawn(async move {
let result = cache_clone
- .extract_frames_batch(start, end, extract_tx)
+ .extract_frames_batch(start, end, extract_tx, descending)
.await;
debug!("extraction task completed: {:?}", result.is_ok());
result
@@ -738,6 +749,7 @@ async fn extract_frame(
break;
}
+ let (frame, _) = &tasks[task_index];
let frame_data = &all_frames[task_index];
let cache_key = format!("{}||{}", chunk.timestamp, device_data.device_name);
debug!("processing frame {} with key {}", task_index, cache_key);
@@ -767,6 +779,7 @@ async fn extract_frame(
error: None,
timestamp: chunk.timestamp,
frame_data: vec![DeviceFrame {
+ frame_id: frame.frame_id,
device_id: device_data.device_name.clone(),
image_data: frame_data.clone(),
metadata: FrameMetadata {
diff --git a/screenpipe-server/src/video_utils.rs b/screenpipe-server/src/video_utils.rs
index 39c666537..d64bff640 100644
--- a/screenpipe-server/src/video_utils.rs
+++ b/screenpipe-server/src/video_utils.rs
@@ -52,12 +52,16 @@ pub async fn extract_frame(file_path: &str, offset_index: i64) -> Result<String>
&offset_str,
"-i",
file_path,
+ "-vf",
+ "scale=iw*0.75:ih*0.75", // Scale down to 75% of original size
"-vframes",
"1",
"-f",
"image2pipe",
- "-vcodec",
- "mjpeg",
+ "-c:v",
+ "mjpeg", // Use JPEG instead of PNG for smaller size
+ "-q:v",
+ "10", // Compression quality (2-31, lower is better quality)
"-",
])
.stdout(std::process::Stdio::piped())
@@ -507,3 +511,89 @@ impl VideoMetadataOverride {
}
}
}
+
+pub async fn extract_frame_from_video(file_path: &str, offset_index: i64) -> Result<String> {
+ let ffmpeg_path = find_ffmpeg_path().expect("failed to find ffmpeg path");
+
+ let offset_seconds = offset_index as f64 / 1000.0;
+ let offset_str = format!("{:.3}", offset_seconds);
+
+ // Create a temporary directory for frames if it doesn't exist
+ let frames_dir = PathBuf::from("/tmp/screenpipe_frames");
+ tokio::fs::create_dir_all(&frames_dir).await?;
+
+ // Generate unique filename for the frame
+ let frame_filename = format!("frame_{}_{}.jpg", offset_index, Uuid::new_v4());
+ let output_path = frames_dir.join(&frame_filename);
+
+ debug!(
+ "extracting frame from {} at offset {} to {}",
+ file_path,
+ offset_str,
+ output_path.display()
+ );
+
+ let mut command = Command::new(ffmpeg_path);
+ command
+ .args([
+ "-ss",
+ &offset_str,
+ "-i",
+ file_path,
+ "-vf",
+ "scale=iw*0.75:ih*0.75",
+ "-vframes",
+ "1",
+ "-c:v",
+ "mjpeg",
+ "-q:v",
+ "10",
+ output_path.to_str().unwrap(),
+ ])
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped());
+
+ debug!("ffmpeg command: {:?}", command);
+
+ let output = command.output().await?;
+
+ if !output.status.success() {
+ let error_message = String::from_utf8_lossy(&output.stderr);
+ info!("ffmpeg error: {}", error_message);
+ return Err(anyhow::anyhow!("ffmpeg process failed: {}", error_message));
+ }
+
+ if !output_path.exists() {
+ return Err(anyhow::anyhow!("failed to extract frame: file not created"));
+ }
+
+ // Schedule cleanup of old frames (files older than 1 hour)
+ tokio::spawn(async move {
+ if let Err(e) = cleanup_old_frames(&frames_dir).await {
+ error!("Failed to cleanup old frames: {}", e);
+ }
+ });
+
+ Ok(output_path.to_string_lossy().into_owned())
+}
+
+async fn cleanup_old_frames(frames_dir: &PathBuf) -> Result<()> {
+ use std::time::{Duration, SystemTime};
+
+ let one_hour_ago = SystemTime::now() - Duration::from_secs(3600);
+ let mut read_dir = tokio::fs::read_dir(frames_dir).await?;
+
+ while let Some(entry) = read_dir.next_entry().await? {
+ if let Ok(metadata) = entry.metadata().await {
+ if let Ok(modified) = metadata.modified() {
+ if modified < one_hour_ago {
+ if let Err(e) = tokio::fs::remove_file(entry.path()).await {
+ error!("Failed to remove old frame: {}", e);
+ }
+ }
+ }
+ }
+ }
+
+ Ok(())
+}