Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix: timeline selection

Louis Beaumontd760d4ca93a0
diff --git a/screenpipe-app-tauri/app/timeline/page.tsx b/screenpipe-app-tauri/app/timeline/page.tsx
index 36bf859c5..3b3988d03 100644
--- a/screenpipe-app-tauri/app/timeline/page.tsx
+++ b/screenpipe-app-tauri/app/timeline/page.tsx
@@ -1,31 +1,15 @@
"use client";
-import { useEffect, useState, useRef } from "react";
-import { OpenAI } from "openai";
-import { generateId, Message } from "ai";
+import { useEffect, useState, useRef, useMemo } from "react";
import { useSettings } from "@/lib/hooks/use-settings";
-import { ChatMessage } from "@/components/chat-message-v2";
-import { useToast } from "@/components/ui/use-toast";
-import { ChatCompletionMessageParam } from "openai/resources/index.mjs";
-import {
- Loader2,
- Send,
- Square,
- X,
- GripHorizontal,
- RotateCcw,
- AlertCircle,
-} from "lucide-react";
-import { Input } from "@/components/ui/input";
-import { Button } from "@/components/ui/button";
-import { platform } from "@tauri-apps/plugin-os";
+import { Loader2, RotateCcw, AlertCircle } from "lucide-react";
import posthog from "posthog-js";
import { TimelineBlocks } from "@/components/timeline/timeline-block";
-import {
- TimelineDock,
- TimelineDockIcon,
- TimelineIconsSection,
-} from "@/components/timeline/timeline-dock";
+import { TimelineIconsSection } from "@/components/timeline/timeline-dock";
import { AudioTranscript } from "@/components/timeline/audio-transcript";
+import { AIPanel } from "@/components/timeline/ai-panel";
+import { TimelineProvider } from "@/lib/hooks/use-timeline-selection";
+import { throttle } from "lodash";
+import { AGENTS } from "@/components/timeline/agents";
export interface StreamTimeSeriesResponse {
timestamp: string;
@@ -59,274 +43,8 @@ export interface AudioData {
interface TimeRange {
start: Date;
end: Date;
- visibleStart?: Date;
- visibleEnd?: Date;
}
-interface Agent {
- id: string;
- name: string;
- description: string;
- analyze: (
- frames: StreamTimeSeriesResponse[],
- openai: OpenAI,
- options: {
- model: string;
- onProgress: (chunk: string) => void;
- }
- ) => Promise<void>;
-}
-
-async function streamCompletion(
- openai: OpenAI,
- messages: ChatCompletionMessageParam[],
- options: {
- model: string;
- onProgress: (chunk: string) => void;
- }
-) {
- console.log("streaming completion", messages);
- const stream = await openai.chat.completions.create({
- model: options.model,
- messages,
- stream: true,
- });
-
- let fullResponse = "";
- for await (const chunk of stream) {
- const content = chunk.choices[0]?.delta?.content || "";
- fullResponse += content;
- options.onProgress(fullResponse);
- }
-}
-
-async function analyzeChunk(
- chunk: any[],
- openai: OpenAI,
- model: string
-): Promise<string> {
- const response = await openai.chat.completions.create({
- model,
- messages: [
- {
- role: "system",
- content:
- "summarize this chunk of activity in 2-3 sentences, focus on key events and patterns",
- },
- {
- role: "user",
- content: JSON.stringify(chunk),
- },
- ],
- });
- return response.choices[0]?.message?.content || "";
-}
-
-const AGENTS: Agent[] = [
- {
- id: "recursive-summarizer",
- name: "recursive summarizer",
- description: "good at processing long time ranges but quality decreases with shorter time ranges",
- analyze: async (frames, openai, { model, onProgress = () => {} }) => {
- if (!frames.length) {
- onProgress("no frames to analyze\n\n");
- return;
- }
-
- onProgress("analyzing chunks...\n\n");
-
- const chunkSize = 5 * 60 * 1000;
- const chunks: any[] = [];
- let currentChunk: any[] = [];
-
- frames.forEach((frame) => {
- const frameTime = new Date(frame.timestamp);
- if (
- currentChunk.length === 0 ||
- frameTime.getTime() - new Date(currentChunk[0].timestamp).getTime() <
- chunkSize
- ) {
- currentChunk.push({
- timestamp: frame.timestamp,
- apps: frame.devices.map((d) => d.metadata.app_name),
- windows: frame.devices.map((d) => d.metadata.window_name),
- text: frame.devices.map((d) => d.metadata.ocr_text).filter(Boolean),
- audio: frame.devices.flatMap((d) => d.audio),
- });
- } else {
- chunks.push(currentChunk);
- currentChunk = [frame];
- }
- });
-
- if (currentChunk.length > 0) {
- chunks.push(currentChunk);
- }
-
- const chunkSummaries = await Promise.all(
- chunks.map(async (chunk, index) => {
- const summary = await analyzeChunk(chunk, openai, model);
- onProgress(`chunk ${index + 1}/${chunks.length}: ${summary}\n`);
- return {
- time: new Date(chunk[0].timestamp).toLocaleTimeString(),
- summary,
- };
- })
- );
-
- onProgress("\ncreating final summary...\n\n");
-
- await streamCompletion(
- openai,
- [
- {
- role: "system",
- content: `create a hierarchical summary with these sections:
- ### overview
- (one paragraph summary of entire time range)
-
- ### timeline
- (list of chunk summaries with timestamps)
-
- ### patterns
- (key patterns or insights across chunks)`,
- },
- {
- role: "user",
- content: JSON.stringify({
- timeRange: {
- start: new Date(frames[frames.length - 1].timestamp).toLocaleTimeString(),
- end: new Date(frames[0].timestamp).toLocaleTimeString(),
- },
- chunkSummaries,
- }),
- },
- ],
- { model, onProgress }
- );
- },
- },
- {
- id: "context-master",
- name: "context master",
- description: "analyzes everything: apps, windows, text & audio",
- analyze: async (frames, openai, { model, onProgress }) => {
- const contextData = frames.map((frame) => ({
- timestamp: frame.timestamp,
- devices: frame.devices.map((device) => ({
- device_id: device.device_id,
- metadata: device.metadata,
- audio: device.audio,
- })),
- }));
-
- console.log("context data", contextData);
-
- await streamCompletion(
- openai,
- [
- {
- role: "system",
- content:
- "analyze all context including apps, windows, text & audio. provide insights about user activity patterns",
- },
- {
- role: "user",
- content: JSON.stringify(contextData),
- },
- ],
- { model, onProgress }
- );
- },
- },
- {
- id: "window-tracker",
- name: "window tracker",
- description: "focuses on app & window usage data",
- analyze: async (frames, openai, { model, onProgress }) => {
- const windowData = frames.map((frame) => ({
- timestamp: frame.timestamp,
- windows: frame.devices.map((device) => ({
- app: device.metadata.app_name,
- window: device.metadata.window_name,
- })),
- }));
-
- await streamCompletion(
- openai,
- [
- {
- role: "system",
- content:
- "analyze app and window usage patterns, focus on work habits and application transitions",
- },
- {
- role: "user",
- content: JSON.stringify(windowData),
- },
- ],
- { model, onProgress }
- );
- },
- },
- {
- id: "text-scanner",
- name: "text scanner",
- description: "analyzes visible text (OCR)",
- analyze: async (frames, openai, { model, onProgress }) => {
- const textData = frames.map((frame) => ({
- timestamp: frame.timestamp,
- text: frame.devices
- .map((device) => device.metadata.ocr_text)
- .filter(Boolean),
- }));
-
- await streamCompletion(
- openai,
- [
- {
- role: "system",
- content:
- "analyze OCR text content, identify key topics and information being viewed",
- },
- {
- role: "user",
- content: JSON.stringify(textData),
- },
- ],
- { model, onProgress }
- );
- },
- },
- {
- id: "voice-analyzer",
- name: "voice analyzer",
- description: "focuses on audio transcriptions",
- analyze: async (frames, openai, { model, onProgress }) => {
- const audioData = frames.map((frame) => ({
- timestamp: frame.timestamp,
- audio: frame.devices.flatMap((device) => device.audio),
- }));
-
- await streamCompletion(
- openai,
- [
- {
- role: "system",
- content:
- "analyze audio transcriptions, identify key conversations and spoken content",
- },
- {
- role: "user",
- content: JSON.stringify(audioData),
- },
- ],
- { model, onProgress }
- );
- },
- },
-];
-
export default function Timeline() {
const [currentFrame, setCurrentFrame] = useState<DeviceFrameResponse | null>(
null
@@ -335,41 +53,19 @@ export default function Timeline() {
const [currentIndex, setCurrentIndex] = useState(0);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
- const [loadedTimeRange, setLoadedTimeRange] = useState<{
- start: Date;
- end: Date;
- visibleStart?: Date;
- visibleEnd?: Date;
- } | null>(null);
const eventSourceRef = useRef<EventSource | null>(null);
const retryTimeoutRef = useRef<NodeJS.Timeout>();
const retryCount = useRef(0);
- const [isDragging, setIsDragging] = useState(false);
- const [selectionRange, setSelectionRange] = useState<TimeRange | null>(null);
- const [dragStart, setDragStart] = useState<number | null>(null);
+ const [loadedTimeRange, setLoadedTimeRange] = useState<TimeRange | null>(
+ null
+ );
const { settings } = useSettings();
- const { toast } = useToast();
- const [chatMessages, setChatMessages] = useState<Array<Message>>([]);
- const [isAiLoading, setIsAiLoading] = useState(false);
- const [isStreaming, setIsStreaming] = useState(false);
- const abortControllerRef = useRef<AbortController | null>(null);
const [isAiPanelExpanded, setIsAiPanelExpanded] = useState(false);
- const [aiInput, setAiInput] = useState("");
- const inputRef = useRef<HTMLInputElement>(null);
const aiPanelRef = useRef<HTMLDivElement>(null);
const [position, setPosition] = useState({
- x: window.innerWidth - 400,
- y: window.innerHeight / 4,
- });
- const [isDraggingPanel, setIsDraggingPanel] = useState(false);
- const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
- const [osType, setOsType] = useState<string>("");
- const [selectedAgent, setSelectedAgent] = useState<Agent>(AGENTS[0]);
- const [chatWindowSize, setChatWindowSize] = useState({
- width: 400,
- height: 500,
+ x: 0,
+ y: 0,
});
- const resizerRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
setPosition({
@@ -388,19 +84,11 @@ export default function Timeline() {
const startTime = new Date();
startTime.setHours(0, 1, 0, 0);
- const visibleStart = new Date();
- visibleStart.setHours(0, 0, 0, 0);
- if (endTime < visibleStart) {
- visibleStart.setDate(visibleStart.getDate() - 1);
- }
-
const url = `http://localhost:3030/stream/frames?start_time=${startTime.toISOString()}&end_time=${endTime.toISOString()}&order=descending`;
setLoadedTimeRange({
start: startTime,
end: endTime,
- visibleStart,
- visibleEnd: endTime,
});
console.log("starting stream:", url);
@@ -427,19 +115,31 @@ export default function Timeline() {
if (!current) return null;
return {
...current,
- visibleStart: frameTime,
- visibleEnd: current.end,
+ start: frameTime,
+ end: current.end,
};
});
+ return [data];
}
- const newFrames = [...prev, data].sort((a, b) => {
- return (
- new Date(b.timestamp).getTime() -
- new Date(a.timestamp).getTime()
- );
- });
+ // 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;
});
@@ -484,259 +184,60 @@ export default function Timeline() {
};
}, []);
- useEffect(() => {
- setOsType(platform());
- }, []);
+ const handleScroll = useMemo(
+ () =>
+ throttle((e: React.WheelEvent<HTMLDivElement>) => {
+ const isWithinAiPanel = aiPanelRef.current?.contains(e.target as Node);
+ const isWithinAudioPanel = document
+ .querySelector(".audio-transcript-panel")
+ ?.contains(e.target as Node);
- useEffect(() => {
- const handleKeyDown = (e: KeyboardEvent) => {
- if ((e.metaKey || e.ctrlKey) && e.key === "k") {
- e.preventDefault();
- if (selectionRange) {
- handleAskAI();
+ if (isWithinAiPanel || isWithinAudioPanel) {
+ return;
}
- }
- if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
e.preventDefault();
- if (isAiPanelExpanded && aiInput.trim()) {
- handleAiSubmit(e as unknown as React.FormEvent);
+ e.stopPropagation();
+
+ const scrollSensitivity = 1;
+ const delta = -Math.sign(e.deltaY) / scrollSensitivity;
+
+ const newIndex = Math.min(
+ Math.max(
+ 0,
+ currentIndex + (delta > 0 ? Math.ceil(delta) : Math.floor(delta))
+ ),
+ frames.length - 1
+ );
+
+ if (newIndex !== currentIndex) {
+ setCurrentIndex(newIndex);
+ frames[newIndex] && setCurrentFrame(frames[newIndex].devices[0]);
}
- }
- };
-
- window.addEventListener("keydown", handleKeyDown);
- return () => window.removeEventListener("keydown", handleKeyDown);
- }, [selectionRange, isAiPanelExpanded, aiInput]);
-
- const handleScroll = (e: React.WheelEvent<HTMLDivElement>) => {
- const isWithinAiPanel = aiPanelRef.current?.contains(e.target as Node);
- const isWithinAudioPanel = document
- .querySelector(".audio-transcript-panel")
- ?.contains(e.target as Node);
-
- if (isWithinAiPanel || isWithinAudioPanel) {
- return;
- }
-
- e.preventDefault();
- e.stopPropagation();
-
- const scrollSensitivity = 1;
- const delta = -Math.sign(e.deltaY) / scrollSensitivity;
-
- const newIndex = Math.min(
- Math.max(
- 0,
- currentIndex + (delta > 0 ? Math.ceil(delta) : Math.floor(delta))
- ),
- frames.length - 1
- );
-
- if (newIndex !== currentIndex) {
- setCurrentIndex(newIndex);
- setCurrentFrame(frames[newIndex].devices[0]);
- }
- };
+ }, 16), // Throttle to ~60fps
+ [currentIndex, frames]
+ );
- const getCurrentTimePercentage = () => {
- if (!currentFrame || !loadedTimeRange) return 0;
+ const timePercentage = useMemo(() => {
+ if (
+ !currentFrame ||
+ !loadedTimeRange ||
+ !frames.length ||
+ currentIndex >= frames.length
+ )
+ return 0;
const frameTime = new Date(
currentFrame.metadata.timestamp || frames[currentIndex].timestamp
);
const totalVisibleMilliseconds =
- (loadedTimeRange.visibleEnd?.getTime() || 0) -
- (loadedTimeRange.visibleStart?.getTime() || 0);
+ loadedTimeRange.end.getTime() - loadedTimeRange.start.getTime();
const currentMilliseconds =
- frameTime.getTime() - (loadedTimeRange.visibleStart?.getTime() || 0);
+ frameTime.getTime() - loadedTimeRange.start.getTime();
return (currentMilliseconds / totalVisibleMilliseconds) * 100;
- };
-
- const handleTimelineMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
- if (!e.currentTarget) return;
-
- const rect = e.currentTarget.getBoundingClientRect();
- const clickX = e.clientX - rect.left;
- const percentage = (clickX / rect.width) * 100;
-
- // Clamp percentage between 0 and 100
- const clampedPercentage = Math.max(0, Math.min(100, percentage));
-
- setIsDragging(true);
- setDragStart(clampedPercentage);
-
- const totalMinutesInDay = 24 * 60;
- const minutesFromMidnight = (clampedPercentage / 100) * totalMinutesInDay;
- const hours = Math.floor(minutesFromMidnight / 60);
- const minutes = Math.floor(minutesFromMidnight % 60);
-
- const localDate = new Date();
- localDate.setHours(hours, minutes, 0, 0);
-
- const utcDate = new Date(
- Date.UTC(
- localDate.getUTCFullYear(),
- localDate.getUTCMonth(),
- localDate.getUTCDate(),
- localDate.getUTCHours(),
- localDate.getUTCMinutes(),
- 0,
- 0
- )
- );
-
- setSelectionRange({
- start: utcDate,
- end: utcDate,
- });
- };
-
- const handleTimelineMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
- if (!isDragging || dragStart === null || !e.currentTarget) return;
-
- e.preventDefault();
- const rect = e.currentTarget.getBoundingClientRect();
- const moveX = e.clientX - rect.left;
- const percentage = (moveX / rect.width) * 100;
-
- // Clamp percentage between 0 and 100
- const clampedPercentage = Math.max(0, Math.min(100, percentage));
-
- const totalMinutesInDay = 24 * 60;
- const startMinutes =
- (Math.min(dragStart, clampedPercentage) / 100) * totalMinutesInDay;
- const endMinutes =
- (Math.max(dragStart, clampedPercentage) / 100) * totalMinutesInDay;
-
- const startLocal = new Date();
- startLocal.setHours(
- Math.floor(startMinutes / 60),
- Math.floor(startMinutes % 60),
- 0,
- 0
- );
-
- const endLocal = new Date();
- endLocal.setHours(
- Math.floor(endMinutes / 60),
- Math.floor(endMinutes % 60),
- 0,
- 0
- );
-
- const utcStartDate = new Date(
- Date.UTC(
- startLocal.getUTCFullYear(),
- startLocal.getUTCMonth(),
- startLocal.getUTCDate(),
- startLocal.getUTCHours(),
- startLocal.getUTCMinutes(),
- 0,
- 0
- )
- );
-
- const utcEndDate = new Date(
- Date.UTC(
- endLocal.getUTCFullYear(),
- endLocal.getUTCMonth(),
- endLocal.getUTCDate(),
- endLocal.getUTCHours(),
- endLocal.getUTCMinutes(),
- 0,
- 0
- )
- );
-
- setSelectionRange({
- start: utcStartDate,
- end: utcEndDate,
- });
- };
-
- const handleTimelineMouseUp = () => {
- setIsDragging(false);
- setDragStart(null);
- };
-
- const handleAskAI = () => {
- posthog.capture("timeline_toggle_ai_panel", {
- action: isAiPanelExpanded ? "close" : "open",
- });
-
- if (isAiPanelExpanded) {
- setChatMessages([]);
- setIsAiPanelExpanded(false);
- setAiInput("");
- } else {
- setChatMessages([]);
- setIsAiPanelExpanded(true);
- setTimeout(() => {
- inputRef.current?.focus();
- }, 100);
- }
- };
-
- const handleAiSubmit = async (e: React.FormEvent) => {
- e.preventDefault();
- if (!aiInput.trim() || !selectionRange) return;
-
- const relevantFrames = frames.filter((frame) => {
- const frameTime = new Date(frame.timestamp);
- return (
- frameTime >= selectionRange.start && frameTime <= selectionRange.end
- );
- });
-
- console.log("relevant frames", relevantFrames);
-
- const userMessage = {
- id: generateId(),
- role: "user" as const,
- content: aiInput,
- };
- setChatMessages((prev) => [...prev, userMessage]);
- setAiInput("");
- setIsAiLoading(true);
-
- try {
- const openai = new OpenAI({
- apiKey: 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 },
- ]);
- },
- });
- } catch (error) {
- 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);
- }
- };
+ }, [currentFrame, loadedTimeRange, currentIndex, frames]);
useEffect(() => {
const preventScroll = (e: WheelEvent) => {
@@ -750,47 +251,6 @@ export default function Timeline() {
return () => document.removeEventListener("wheel", preventScroll);
}, []);
- 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;
-
- setPosition({
- 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]);
-
const handleRefresh = () => {
posthog.capture("timeline_refresh");
@@ -802,349 +262,166 @@ export default function Timeline() {
setupEventSource();
};
- const handleAgentChange = (agentId: string) => {
- const newAgent = AGENTS.find((a) => a.id === agentId) || AGENTS[0];
- posthog.capture("timeline_change_agent", {
- agent: newAgent.name,
- });
- setSelectedAgent(newAgent);
- };
-
- 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); // Minimum width
- const newHeight = Math.max(200, startHeight + moveEvent.clientY - startY); // Minimum height
- setChatWindowSize({ width: newWidth, height: newHeight });
- };
-
- const handleMouseUp = () => {
- document.removeEventListener("mousemove", handleMouseMove);
- document.removeEventListener("mouseup", handleMouseUp);
- };
-
- document.addEventListener("mousemove", handleMouseMove);
- document.addEventListener("mouseup", handleMouseUp);
- };
-
return (
- <div
- className="fixed inset-0 flex flex-col bg-background text-foreground overflow-hidden relative"
- onWheel={(e) => {
- const isWithinAiPanel = aiPanelRef.current?.contains(e.target as Node);
- if (!isWithinAiPanel) {
- handleScroll(e);
- }
- }}
- style={{
- height: "100vh",
- overscrollBehavior: "none",
- WebkitUserSelect: "none",
- userSelect: "none",
- MozUserSelect: "none",
- msUserSelect: "none",
- }}
- >
- <button
- onClick={handleRefresh}
- className="absolute top-4 right-4 p-2 text-foreground hover:text-foreground/70 bg-background rounded border border-muted-foreground hover:border-foreground/50 transition-colors z-50"
- >
- <RotateCcw className="h-4 w-4" />
- </button>
-
+ <TimelineProvider>
<div
- className="fixed inset-0 pointer-events-none z-50"
+ className="fixed inset-0 flex flex-col bg-background text-foreground overflow-hidden relative"
+ onWheel={(e) => {
+ const isWithinAiPanel = aiPanelRef.current?.contains(
+ e.target as Node
+ );
+ if (!isWithinAiPanel) {
+ handleScroll(e);
+ }
+ }}
style={{
- background:
- "repeating-linear-gradient(0deg, rgba(0,0,0,0.1) 0px, rgba(0,0,0,0.1) 1px, transparent 1px, transparent 2px)",
+ height: "100vh",
+ overscrollBehavior: "none",
+ WebkitUserSelect: "none",
+ userSelect: "none",
+ MozUserSelect: "none",
+ msUserSelect: "none",
}}
- />
-
- <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>
- )}
- {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">
- <AlertCircle className="h-4 w-4 mb-2 mx-auto" />
- <p>{error}</p>
- </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"
- alt="Current frame"
- />
- )}
- {currentFrame && (
- <AudioTranscript
- frames={frames}
- currentIndex={currentIndex}
- groupingWindowMs={30000} // 30 seconds window
- />
- )}
- </div>
+ >
+ <button
+ onClick={handleRefresh}
+ className="absolute top-4 right-4 p-2 text-foreground hover:text-foreground/70 bg-background rounded border border-muted-foreground hover:border-foreground/50 transition-colors z-50"
+ >
+ <RotateCcw className="h-4 w-4" />
+ </button>
- <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"
- onMouseDown={handleTimelineMouseDown}
- onMouseMove={handleTimelineMouseMove}
- onMouseUp={handleTimelineMouseUp}
- >
- {loadedTimeRange && (
- <div className="relative h-full bg-muted rounded-md overflow-hidden">
- <TimelineBlocks frames={frames} timeRange={loadedTimeRange} />
+ className="fixed inset-0 pointer-events-none z-50"
+ style={{
+ background:
+ "repeating-linear-gradient(0deg, rgba(0,0,0,0.1) 0px, rgba(0,0,0,0.1) 1px, transparent 1px, transparent 2px)",
+ }}
+ />
+
+ <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>
)}
-
- <div
- className="absolute inset-0"
- style={{
- background:
- "linear-gradient(90deg, rgba(0,255,0,0.1) 1px, transparent 1px)",
- backgroundSize: "10% 100%",
- }}
- />
-
- <div
- className="absolute top-0 h-full w-1 bg-foreground/50 shadow-sm opacity-80 z-10"
- style={{ left: `${getCurrentTimePercentage()}%` }}
- >
- <div className="relative -top-6 right-3 text-[10px] text-muted-foreground whitespace-nowrap">
- {frames[currentIndex] &&
- new Date(frames[currentIndex].timestamp).toLocaleTimeString(
- [],
- {
- hour: "2-digit",
- minute: "2-digit",
- second: "2-digit",
- }
- )}
+ {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">
+ <AlertCircle className="h-4 w-4 mb-2 mx-auto" />
+ <p>{error}</p>
+ </div>
</div>
- </div>
-
- {selectionRange && (
- <div
- className="absolute top-0 h-full bg-foreground/10"
- style={{
- left: `${
- (new Date(selectionRange.start).getHours() * 3600 +
- new Date(selectionRange.start).getMinutes() * 60) /
- 864
- }%`,
- width: `${
- ((selectionRange.end.getTime() -
- selectionRange.start.getTime()) /
- (24 * 3600 * 1000)) *
- 100
- }%`,
- }}
+ )}
+ {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-2"
+ alt="Current frame"
+ />
+ )}
+ {currentFrame && (
+ <AudioTranscript
+ frames={frames}
+ currentIndex={currentIndex}
+ groupingWindowMs={30000} // 30 seconds window
/>
)}
</div>
- {selectionRange && (
- <div
- ref={aiPanelRef}
- style={{
- position: "fixed",
- left: position.x,
- top: position.y,
- width: chatWindowSize.width,
- height: isAiPanelExpanded ? chatWindowSize.height : 120,
- cursor: isDraggingPanel ? "grabbing" : "default",
- }}
- className="bg-background border border-muted-foreground rounded-lg shadow-lg transition-all duration-300 ease-in-out z-[100]"
- >
+ <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">
+ <div className="relative h-full bg-muted rounded-md overflow-hidden">
+ {loadedTimeRange && (
+ <TimelineBlocks frames={frames} timeRange={loadedTimeRange!} />
+ )}
+ </div>
+
<div
- className="select-none cursor-grab active:cursor-grabbing"
- onMouseDown={handlePanelMouseDown}
+ className="absolute top-0 h-full w-1 bg-foreground/50 shadow-sm opacity-80 z-10"
+ style={{ left: `${timePercentage}%` }}
>
- <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.getTime()
- ).toLocaleTimeString()}{" "}
- -{" "}
- {new Date(
- selectionRange.end.getTime()
- ).toLocaleTimeString()}
- </div>
- </div>
- <button
- onClick={() => {
- setSelectionRange(null);
- setIsAiPanelExpanded(false);
- setChatMessages([]);
- setAiInput("");
- }}
- className="text-muted-foreground hover:text-foreground transition-colors ml-2"
- >
- <X className="h-4 w-4" />
- </button>
+ <div className="relative -top-6 right-3 text-[10px] text-muted-foreground whitespace-nowrap">
+ {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>
-
- {!isAiPanelExpanded && (
- <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();
- setIsAiPanelExpanded(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>
+ </div>
+
+ <AIPanel
+ position={position}
+ onPositionChange={setPosition}
+ onClose={() => {
+ setIsAiPanelExpanded(false);
+ }}
+ frames={frames}
+ agents={AGENTS}
+ settings={settings}
+ isExpanded={isAiPanelExpanded}
+ onExpandedChange={setIsAiPanelExpanded}
+ />
- {isAiPanelExpanded && (
- <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",
- }}
- >
- {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>
+ {loadedTimeRange && frames.length > 0 && (
+ <TimelineIconsSection blocks={frames} />
+ )}
- <form
- onSubmit={handleAiSubmit}
- className="p-3 border-t border-muted-foreground"
- >
- <div className="flex flex-col gap-2">
- <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 className="flex gap-2">
- <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}
- />
- <Button
- type="submit"
- variant="outline"
- className="hover:bg-accent transition-colors"
- disabled={isAiLoading}
- >
- {isStreaming ? (
- <Square className="h-4 w-4" />
- ) : (
- <Send className="h-4 w-4" />
- )}
- </Button>
- </div>
+ <div className="relative mt-1 px-2 text-[10px] text-muted-foreground select-none">
+ {Array(7)
+ .fill(0)
+ .map((_, i) => {
+ if (!loadedTimeRange) return null;
+ const totalMinutes =
+ (loadedTimeRange.end.getTime() -
+ loadedTimeRange.start.getTime()) /
+ (1000 * 60);
+ const minutesPerStep = totalMinutes / 6;
+ const date = new Date(
+ loadedTimeRange.start.getTime() +
+ i * minutesPerStep * 60 * 1000
+ );
+ return (
+ <div
+ key={i}
+ className="absolute transform -translate-x-1/2"
+ style={{ left: `${(i * 100) / 6}%` }}
+ >
+ {date.toLocaleTimeString([], {
+ hour: "2-digit",
+ minute: "2-digit",
+ })}
</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>
- )}
-
- {loadedTimeRange && frames.length > 0 && (
- <TimelineIconsSection blocks={frames} />
- )}
-
- <div className="relative mt-1 px-2 text-[10px] text-muted-foreground select-none">
- {Array(7)
- .fill(0)
- .map((_, i) => {
- if (!loadedTimeRange) return null;
- const totalMinutes =
- (loadedTimeRange.visibleEnd!.getTime() -
- loadedTimeRange.visibleStart!.getTime()) /
- (1000 * 60);
- const minutesPerStep = totalMinutes / 6;
- const date = new Date(
- loadedTimeRange.visibleStart!.getTime() +
- i * minutesPerStep * 60 * 1000
- );
- return (
- <div
- key={i}
- className="absolute transform -translate-x-1/2"
- style={{ left: `${(i * 100) / 6}%` }}
- >
- {date.toLocaleTimeString([], {
- hour: "2-digit",
- minute: "2-digit",
- })}
- </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 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>
- </div>
+ </TimelineProvider>
);
}
diff --git a/screenpipe-app-tauri/components/timeline/agents.tsx b/screenpipe-app-tauri/components/timeline/agents.tsx
new file mode 100644
index 000000000..c55921590
--- /dev/null
+++ b/screenpipe-app-tauri/components/timeline/agents.tsx
@@ -0,0 +1,270 @@
+import { StreamTimeSeriesResponse } from "@/app/timeline/page";
+import OpenAI from "openai";
+import { ChatCompletionMessageParam } from "openai/resources/index.mjs";
+
+interface Agent {
+ id: string;
+ name: string;
+ description: string;
+ analyze: (
+ frames: StreamTimeSeriesResponse[],
+ openai: OpenAI,
+ options: {
+ model: string;
+ onProgress: (chunk: string) => void;
+ }
+ ) => Promise<void>;
+}
+
+async function streamCompletion(
+ openai: OpenAI,
+ messages: ChatCompletionMessageParam[],
+ options: {
+ model: string;
+ onProgress: (chunk: string) => void;
+ }
+) {
+ console.log("streaming completion", messages);
+ const stream = await openai.chat.completions.create({
+ model: options.model,
+ messages,
+ stream: true,
+ });
+
+ let fullResponse = "";
+ for await (const chunk of stream) {
+ const content = chunk.choices[0]?.delta?.content || "";
+ fullResponse += content;
+ options.onProgress(fullResponse);
+ }
+}
+
+export async function analyzeChunk(
+ chunk: any[],
+ openai: OpenAI,
+ model: string
+): Promise<string> {
+ const response = await openai.chat.completions.create({
+ model,
+ messages: [
+ {
+ role: "system",
+ content:
+ "summarize this chunk of activity in 2-3 sentences, focus on key events and patterns",
+ },
+ {
+ role: "user",
+ content: JSON.stringify(chunk),
+ },
+ ],
+ });
+ return response.choices[0]?.message?.content || "";
+}
+
+export const AGENTS: Agent[] = [
+ {
+ id: "recursive-summarizer",
+ name: "recursive summarizer",
+ description:
+ "good at processing long time ranges but quality decreases with shorter time ranges",
+ analyze: async (frames, openai, { model, onProgress = () => {} }) => {
+ if (!frames.length) {
+ onProgress("no frames to analyze\n\n");
+ return;
+ }
+
+ onProgress("analyzing chunks...\n\n");
+
+ const chunkSize = 5 * 60 * 1000;
+ const chunks: any[] = [];
+ let currentChunk: any[] = [];
+
+ frames.forEach((frame) => {
+ const frameTime = new Date(frame.timestamp);
+ if (
+ currentChunk.length === 0 ||
+ frameTime.getTime() - new Date(currentChunk[0].timestamp).getTime() <
+ chunkSize
+ ) {
+ currentChunk.push({
+ timestamp: frame.timestamp,
+ apps: frame.devices.map((d) => d.metadata.app_name),
+ windows: frame.devices.map((d) => d.metadata.window_name),
+ text: frame.devices.map((d) => d.metadata.ocr_text).filter(Boolean),
+ audio: frame.devices.flatMap((d) => d.audio),
+ });
+ } else {
+ chunks.push(currentChunk);
+ currentChunk = [frame];
+ }
+ });
+
+ if (currentChunk.length > 0) {
+ chunks.push(currentChunk);
+ }
+
+ const chunkSummaries = await Promise.all(
+ chunks.map(async (chunk, index) => {
+ const summary = await analyzeChunk(chunk, openai, model);
+ onProgress(`chunk ${index + 1}/${chunks.length}: ${summary}\n`);
+ return {
+ time: new Date(chunk[0].timestamp).toLocaleTimeString(),
+ summary,
+ };
+ })
+ );
+
+ onProgress("\ncreating final summary...\n\n");
+
+ await streamCompletion(
+ openai,
+ [
+ {
+ role: "system",
+ content: `create a hierarchical summary with these sections:
+ ### overview
+ (one paragraph summary of entire time range)
+
+ ### timeline
+ (list of chunk summaries with timestamps)
+
+ ### patterns
+ (key patterns or insights across chunks)`,
+ },
+ {
+ role: "user",
+ content: JSON.stringify({
+ timeRange: {
+ start: new Date(
+ frames[frames.length - 1].timestamp
+ ).toLocaleTimeString(),
+ end: new Date(frames[0].timestamp).toLocaleTimeString(),
+ },
+ chunkSummaries,
+ }),
+ },
+ ],
+ { model, onProgress }
+ );
+ },
+ },
+ {
+ id: "context-master",
+ name: "context master",
+ description: "analyzes everything: apps, windows, text & audio",
+ analyze: async (frames, openai, { model, onProgress }) => {
+ const contextData = frames.map((frame) => ({
+ timestamp: frame.timestamp,
+ devices: frame.devices.map((device) => ({
+ device_id: device.device_id,
+ metadata: device.metadata,
+ audio: device.audio,
+ })),
+ }));
+
+ console.log("context data", contextData);
+
+ await streamCompletion(
+ openai,
+ [
+ {
+ role: "system",
+ content:
+ "analyze all context including apps, windows, text & audio. provide insights about user activity patterns",
+ },
+ {
+ role: "user",
+ content: JSON.stringify(contextData),
+ },
+ ],
+ { model, onProgress }
+ );
+ },
+ },
+ {
+ id: "window-tracker",
+ name: "window tracker",
+ description: "focuses on app & window usage data",
+ analyze: async (frames, openai, { model, onProgress }) => {
+ const windowData = frames.map((frame) => ({
+ timestamp: frame.timestamp,
+ windows: frame.devices.map((device) => ({
+ app: device.metadata.app_name,
+ window: device.metadata.window_name,
+ })),
+ }));
+
+ await streamCompletion(
+ openai,
+ [
+ {
+ role: "system",
+ content:
+ "analyze app and window usage patterns, focus on work habits and application transitions",
+ },
+ {
+ role: "user",
+ content: JSON.stringify(windowData),
+ },
+ ],
+ { model, onProgress }
+ );
+ },
+ },
+ {
+ id: "text-scanner",
+ name: "text scanner",
+ description: "analyzes visible text (OCR)",
+ analyze: async (frames, openai, { model, onProgress }) => {
+ const textData = frames.map((frame) => ({
+ timestamp: frame.timestamp,
+ text: frame.devices
+ .map((device) => device.metadata.ocr_text)
+ .filter(Boolean),
+ }));
+
+ await streamCompletion(
+ openai,
+ [
+ {
+ role: "system",
+ content:
+ "analyze OCR text content, identify key topics and information being viewed",
+ },
+ {
+ role: "user",
+ content: JSON.stringify(textData),
+ },
+ ],
+ { model, onProgress }
+ );
+ },
+ },
+ {
+ id: "voice-analyzer",
+ name: "voice analyzer",
+ description: "focuses on audio transcriptions",
+ analyze: async (frames, openai, { model, onProgress }) => {
+ const audioData = frames.map((frame) => ({
+ timestamp: frame.timestamp,
+ audio: frame.devices.flatMap((device) => device.audio),
+ }));
+
+ await streamCompletion(
+ openai,
+ [
+ {
+ role: "system",
+ content:
+ "analyze audio transcriptions, identify key conversations and spoken content",
+ },
+ {
+ role: "user",
+ content: JSON.stringify(audioData),
+ },
+ ],
+ { model, onProgress }
+ );
+ },
+ },
+];
diff --git a/screenpipe-app-tauri/components/timeline/ai-panel.tsx b/screenpipe-app-tauri/components/timeline/ai-panel.tsx
new file mode 100644
index 000000000..1c0ddce3c
--- /dev/null
+++ b/screenpipe-app-tauri/components/timeline/ai-panel.tsx
@@ -0,0 +1,369 @@
+import { useRef, useState, useEffect } from "react";
+import { Message, generateId } from "ai";
+import { OpenAI } from "openai";
+import { ChatMessage } from "@/components/chat-message-v2";
+import { useToast } from "@/components/ui/use-toast";
+import { Input } from "@/components/ui/input";
+import { Button } from "@/components/ui/button";
+import { Loader2, Send, Square, X, GripHorizontal } from "lucide-react";
+import { StreamTimeSeriesResponse } from "@/app/timeline/page";
+import { platform } from "@tauri-apps/plugin-os";
+import posthog from "posthog-js";
+import { useTimelineSelection } from "@/lib/hooks/use-timeline-selection";
+
+interface Agent {
+ id: string;
+ name: string;
+ description: string;
+ analyze: (
+ frames: StreamTimeSeriesResponse[],
+ openai: OpenAI,
+ options: {
+ model: string;
+ onProgress: (chunk: string) => void;
+ }
+ ) => Promise<void>;
+}
+
+interface AIPanelProps {
+ position: { x: number; y: number };
+ onPositionChange: (pos: { x: number; y: number }) => void;
+ onClose: () => void;
+ frames: StreamTimeSeriesResponse[];
+ agents: Agent[];
+ settings: { openaiApiKey: string; aiUrl: string; aiModel: string };
+ isExpanded: boolean;
+ onExpandedChange: (expanded: boolean) => void;
+}
+
+export function AIPanel({
+ position,
+ onPositionChange,
+ onClose,
+ frames,
+ agents,
+ settings,
+ isExpanded,
+ onExpandedChange,
+}: AIPanelProps) {
+ 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 } = useTimelineSelection();
+
+ useEffect(() => {
+ setOsType(platform());
+ }, []);
+
+ 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];
+ posthog.capture("timeline_change_agent", {
+ agent: newAgent.name,
+ });
+ setSelectedAgent(newAgent);
+ };
+
+ const handleAiSubmit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ if (!selectionRange || !aiInput.trim()) return;
+
+ const userMessage = {
+ id: generateId(),
+ role: "user" as const,
+ content: aiInput,
+ };
+ setChatMessages((prev) => [...prev, userMessage]);
+ setAiInput("");
+ setIsAiLoading(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.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 },
+ ]);
+ },
+ });
+ } catch (error) {
+ 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);
+ }
+ };
+
+ const handleClose = () => {
+ setChatMessages([]);
+ setAiInput("");
+ onClose();
+ };
+
+ if (!selectionRange) return null;
+
+ return (
+ <div
+ ref={aiPanelRef}
+ style={{
+ position: "fixed",
+ left: position.x,
+ top: position.y,
+ width: chatWindowSize.width,
+ height: isExpanded ? chatWindowSize.height : 120,
+ cursor: isDraggingPanel ? "grabbing" : "default",
+ }}
+ className="bg-background border border-muted-foreground rounded-lg shadow-lg transition-all duration-300 ease-in-out z-[100]"
+ >
+ <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.getTime()).toLocaleTimeString()} -{" "}
+ {new Date(selectionRange.end.getTime()).toLocaleTimeString()}
+ </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",
+ }}
+ >
+ {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">
+ <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 className="flex gap-2">
+ <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}
+ />
+ <Button
+ type="submit"
+ variant="outline"
+ className="hover:bg-accent transition-colors"
+ disabled={isAiLoading}
+ >
+ {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/screenpipe-app-tauri/components/timeline/chat-panel.tsx b/screenpipe-app-tauri/components/timeline/chat-panel.tsx
deleted file mode 100644
index 5143aab83..000000000
--- a/screenpipe-app-tauri/components/timeline/chat-panel.tsx
+++ /dev/null
@@ -1,329 +0,0 @@
-import { useRef, useState } from "react";
-import { generateId, Message } from "ai";
-import { OpenAI } from "openai";
-import { ChatCompletionMessageParam } from "openai/resources/index.mjs";
-import { Loader2, Send, Square, X, GripHorizontal } from "lucide-react";
-import { Input } from "@/components/ui/input";
-import { Button } from "@/components/ui/button";
-import { ChatMessage } from "@/components/chat-message-v2";
-import { useToast } from "@/components/ui/use-toast";
-
-interface Agent {
- id: string;
- name: string;
- description: string;
- dataSelector: (frames: any[]) => any;
-}
-
-interface ChatPanelProps {
- position: { x: number; y: number };
- size: { width: number; height: number };
- onPositionChange: (pos: { x: number; y: number }) => void;
- onSizeChange: (size: { width: number; height: number }) => void;
- onClose: () => void;
- isExpanded: boolean;
- onExpand: () => void;
- selectionRange: { start: Date; end: Date };
- frames: any[];
- settings: any;
- agents: Agent[];
- osType: string;
-}
-
-export function ChatPanel({
- position,
- size,
- onPositionChange,
- onSizeChange,
- onClose,
- isExpanded,
- onExpand,
- selectionRange,
- frames,
- settings,
- agents,
- osType,
-}: ChatPanelProps) {
- const [messages, setMessages] = useState<Array<Message>>([]);
- const [isLoading, setIsLoading] = useState(false);
- const [isStreaming, setIsStreaming] = useState(false);
- const [input, setInput] = useState("");
- const [selectedAgent, setSelectedAgent] = useState<Agent>(agents[0]);
- const inputRef = useRef<HTMLInputElement>(null);
- const abortControllerRef = useRef<AbortController | null>(null);
- const { toast } = useToast();
-
- // Dragging logic
- const [isDragging, setIsDragging] = useState(false);
- const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
-
- const handlePanelMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
- setIsDragging(true);
- setDragOffset({
- x: e.clientX - position.x,
- y: e.clientY - position.y,
- });
- };
-
- const handlePanelMouseMove = (e: React.MouseEvent) => {
- if (isDragging) {
- onPositionChange({
- x: e.clientX - dragOffset.x,
- y: e.clientY - dragOffset.y,
- });
- }
- };
-
- const handlePanelMouseUp = () => {
- setIsDragging(false);
- };
-
- // Resizing logic
- const handleResizeMouseDown = (e: React.MouseEvent) => {
- e.preventDefault();
- const startX = e.clientX;
- const startY = e.clientY;
- const startWidth = size.width;
- const startHeight = size.height;
-
- const handleMouseMove = (moveEvent: MouseEvent) => {
- const newWidth = Math.max(200, startWidth + moveEvent.clientX - startX);
- const newHeight = Math.max(200, startHeight + moveEvent.clientY - startY);
- onSizeChange({ width: newWidth, height: newHeight });
- };
-
- const handleMouseUp = () => {
- document.removeEventListener("mousemove", handleMouseMove);
- document.removeEventListener("mouseup", handleMouseUp);
- };
-
- document.addEventListener("mousemove", handleMouseMove);
- document.addEventListener("mouseup", handleMouseUp);
- };
-
- const handleSubmit = async (e: React.FormEvent) => {
- e.preventDefault();
- if (!input.trim()) return;
-
- const relevantFrames = frames.filter((frame) => {
- const frameTime = new Date(frame.timestamp);
- return (
- frameTime >= selectionRange.start && frameTime <= selectionRange.end
- );
- });
-
- const contextData = selectedAgent.dataSelector(relevantFrames);
-
- const userMessage = {
- id: crypto.randomUUID(),
- role: "user" as const,
- content: input,
- };
- setMessages((prev) => [...prev, userMessage]);
- setInput("");
- setIsLoading(true);
-
- try {
- const openai = new OpenAI({
- apiKey: settings.openaiApiKey,
- baseURL: settings.aiUrl,
- dangerouslyAllowBrowser: true,
- });
-
- const m: Message[] = [
- {
- id: generateId(),
- role: "system" as const,
- content: `You are a helpful assistant specialized as a "${
- selectedAgent.name
- }" analyzing screen & mic recordings.
- Rules:
- - Current time (JavaScript Date.prototype.toString): ${new Date().toString()}
- - User timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}
- - User timezone offset: ${new Date().getTimezoneOffset()}
- - All timestamps in the context data are in UTC
- - Convert timestamps to local time for human-readable responses
- - Never output UTC time unless explicitly asked
- - Focus on ${selectedAgent.description}
- - Follow the user's instructions carefully & to the letter: ${
- settings.customPrompt
- }`,
- },
- ...messages,
- {
- id: generateId(),
- role: "user" as const,
- content: `Context data: ${JSON.stringify(contextData)}\n${input}`,
- },
- ];
-
- abortControllerRef.current = new AbortController();
- setIsStreaming(true);
-
- const stream = await openai.chat.completions.create(
- {
- model: settings.aiModel,
- messages: m as ChatCompletionMessageParam[],
- stream: true,
- },
- {
- signal: abortControllerRef.current.signal,
- }
- );
-
- let fullResponse = "";
- setMessages((prev) => [
- ...prev,
- { id: generateId(), role: "assistant", content: "" },
- ]);
-
- for await (const chunk of stream) {
- const content = chunk.choices[0]?.delta?.content || "";
- fullResponse += content;
- setMessages((prev) => [
- ...prev.slice(0, -1),
- { id: generateId(), role: "assistant", content: fullResponse },
- ]);
- }
- } catch (error: any) {
- console.error("error generating ai response:", error);
- toast({
- title: "error",
- description: error.message.toLowerCase().includes("maximum context")
- ? "failed to generate ai response. max context length exceeded."
- : "failed to generate ai response. please try again.",
- variant: "destructive",
- });
- } finally {
- setIsLoading(false);
- setIsStreaming(false);
- }
- };
-
- return (
- <div
- style={{
- position: "fixed",
- left: position.x,
- top: position.y,
- width: size.width,
- height: isExpanded ? size.height : 120,
- cursor: isDragging ? "grabbing" : "default",
- }}
- className="bg-background border border-muted-foreground rounded-lg shadow-lg transition-all duration-300 ease-in-out z-[100]"
- >
- <div
- className="select-none cursor-grab active:cursor-grabbing"
- onMouseDown={handlePanelMouseDown}
- onMouseMove={handlePanelMouseMove}
- onMouseUp={handlePanelMouseUp}
- onMouseLeave={handlePanelMouseUp}
- >
- <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">
- {selectionRange.start.toLocaleTimeString()} -{" "}
- {selectionRange.end.toLocaleTimeString()}
- </div>
- </div>
- <button
- onClick={onClose}
- 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={onExpand}
- >
- <span>ask ai</span>
- <span className="text-muted-foreground text-[10px]">
- {osType === "macos" ? "⌘K" : "Ctrl+K"}
- </span>
- </button>
- </div>
- ) : (
- <div className="flex flex-col h-[calc(100%-52px)]">
- <div className="flex-1 min-h-0 overflow-y-auto p-4 space-y-4 hover:cursor-auto text-foreground font-mono text-sm leading-relaxed">
- {messages.map((msg, index) => (
- <ChatMessage key={index} message={msg} />
- ))}
- {isLoading && (
- <div className="flex justify-center">
- <Loader2 className="h-6 w-6 animate-spin text-foreground" />
- </div>
- )}
- </div>
-
- <div className="mt-auto border-t border-muted-foreground">
- <form onSubmit={handleSubmit} className="p-3">
- <div className="flex flex-col gap-2">
- <select
- value={selectedAgent.id}
- onChange={(e) => {
- const agent = agents.find((a) => a.id === e.target.value);
- if (agent) setSelectedAgent(agent);
- }}
- className="w-full bg-background text-foreground border border-muted-foreground rounded px-2 py-1 text-xs focus:outline-none focus:ring-1 focus:ring-foreground"
- >
- {agents.map((agent) => (
- <option
- key={agent.id}
- value={agent.id}
- className="bg-background text-foreground"
- style={{
- backgroundColor: "var(--background)",
- color: "var(--foreground)",
- }}
- >
- {agent.name} - {agent.description}
- </option>
- ))}
- </select>
- <div className="flex gap-2">
- <Input
- ref={inputRef}
- type="text"
- value={input}
- onChange={(e) => setInput(e.target.value)}
- placeholder="ask about this time range..."
- className="flex-1 bg-background border border-muted-foreground text-foreground placeholder-muted-foreground"
- disabled={isLoading}
- />
- <Button
- type="submit"
- variant="outline"
- className="hover:bg-accent transition-colors"
- disabled={isLoading}
- >
- {isStreaming ? (
- <Square className="h-4 w-4" />
- ) : (
- <Send className="h-4 w-4" />
- )}
- </Button>
- </div>
- </div>
- </form>
- </div>
- </div>
- )}
- </div>
-
- <div
- 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>
- );
-}
diff --git a/screenpipe-app-tauri/components/timeline/timeline-block.tsx b/screenpipe-app-tauri/components/timeline/timeline-block.tsx
index b8cace0c1..df6864ad3 100644
--- a/screenpipe-app-tauri/components/timeline/timeline-block.tsx
+++ b/screenpipe-app-tauri/components/timeline/timeline-block.tsx
@@ -1,5 +1,7 @@
import { StreamTimeSeriesResponse } from "@/app/timeline/page";
-import { useMemo } from "react";
+import { useTimelineSelection } from "@/lib/hooks/use-timeline-selection";
+import { debounce } from "lodash";
+import { useMemo, useState, useRef, useEffect } from "react";
interface TimeBlock {
appName: string;
@@ -14,59 +16,80 @@ interface TimelineBlocksProps {
timeRange: {
start: Date;
end: Date;
- visibleStart?: Date;
- visibleEnd?: Date;
};
}
-export function TimelineBlocks({ frames, timeRange }: TimelineBlocksProps) {
- // Cache colors to avoid recalculating
- const colorCache = useMemo(() => new Map<string, string>(), []);
+// First, memoize the color generation function
+const useColorGenerator = () => {
+ return useMemo(() => {
+ const colorCache = new Map<string, string>();
- // Calculate blocks without sampling
- const blocks = useMemo(() => {
- const getAppColor = (appName: string): string => {
+ return (appName: string): string => {
const cached = colorCache.get(appName);
if (cached) return cached;
- // Use a better hash distribution
const hash = Array.from(appName).reduce(
(h, c) => (Math.imul(31, h) + c.charCodeAt(0)) | 0,
0
);
- // Use golden ratio with a larger step for more distinct hues
const golden_ratio = 0.618033988749895;
const hue = ((hash * golden_ratio * 1.5) % 1) * 360;
-
- // Increase saturation and use fixed lightness for better distinction
- const sat = 85 + (hash % 15); // 85-100%
- const light = 60; // Fixed lightness for better visibility
+ const sat = 85 + (hash % 15);
+ const light = 60;
const color = `hsl(${hue}, ${sat}%, ${light}%)`;
colorCache.set(appName, color);
return color;
};
+ }, []); // Empty deps since this never needs to change
+};
+
+export function TimelineBlocks({ frames, timeRange }: TimelineBlocksProps) {
+ const getAppColor = useColorGenerator();
+ const { setSelectionRange } = useTimelineSelection();
+
+ // Memoize the sorted frames
+ const sortedFrames = useMemo(
+ // TODO: this should not be necessary
+ () =>
+ [...frames].sort(
+ (a, b) =>
+ new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
+ ),
+ [frames]
+ );
+
+ // Memoize the block generation with precise dependencies
+ const blocks = useMemo(() => {
if (frames.length === 0) return [];
- const blocks: TimeBlock[] = [];
+ const visibleBlocks: (TimeBlock & { isGap?: boolean })[] = [];
let currentBlock: TimeBlock | null = null;
+ let lastEndTime: Date | null = null;
- // Sort frames by timestamp first
- const sortedFrames = [...frames].sort(
- (a, b) =>
- new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
- );
-
- sortedFrames.forEach((frame) => {
+ for (const frame of sortedFrames) {
const timestamp = new Date(frame.timestamp);
- // Ensure we have devices data
- if (!frame.devices?.[0]?.metadata?.app_name) return;
+ if (!frame.devices?.[0]?.metadata?.app_name) continue;
const appName = frame.devices[0].metadata.app_name;
const windowName = frame.devices[0].metadata.window_name;
- if (timestamp < timeRange.start || timestamp > timeRange.end) return;
+ if (timestamp < timeRange.start || timestamp > timeRange.end) continue;
+
+ // Handle gap detection
+ if (lastEndTime && timestamp.getTime() - lastEndTime.getTime() > 1000) {
+ visibleBlocks.push({
+ appName: "gap",
+ windowName: "No Activity",
+ startTime: lastEndTime,
+ endTime: timestamp,
+ color: "transparent",
+ isGap: true,
+ });
+ }
+
+ // Handle block creation/update
if (!currentBlock) {
currentBlock = {
appName,
@@ -76,7 +99,7 @@ export function TimelineBlocks({ frames, timeRange }: TimelineBlocksProps) {
color: getAppColor(appName),
};
} else if (currentBlock.appName !== appName) {
- blocks.push(currentBlock);
+ visibleBlocks.push(currentBlock);
currentBlock = {
appName,
windowName,
@@ -87,41 +110,143 @@ export function TimelineBlocks({ frames, timeRange }: TimelineBlocksProps) {
} else {
currentBlock.endTime = timestamp;
}
- });
- if (currentBlock) blocks.push(currentBlock);
- return blocks;
- }, [frames, timeRange]);
+ lastEndTime = timestamp;
+ }
- return (
- <div className="absolute inset-0 flex flex-col">
- {blocks.map((block, index) => {
- // Calculate position relative to visible range instead of 24-hour scale
- const visibleStartTime = timeRange.visibleStart || timeRange.start;
- const visibleEndTime = timeRange.visibleEnd || timeRange.end;
- const visibleRangeMs =
- visibleEndTime.getTime() - visibleStartTime.getTime();
+ if (currentBlock) visibleBlocks.push(currentBlock);
- const blockStartMs =
- block.startTime.getTime() - visibleStartTime.getTime();
- const blockDurationMs =
- block.endTime.getTime() - block.startTime.getTime();
+ // Handle edge gaps
+ if (visibleBlocks[0]?.startTime.getTime() > timeRange.start.getTime()) {
+ visibleBlocks.unshift({
+ appName: "gap",
+ windowName: "No Activity",
+ startTime: timeRange.start,
+ endTime: visibleBlocks[0].startTime,
+ color: "transparent",
+ isGap: true,
+ });
+ }
- // Calculate percentages based on visible range
- const blockStart = (blockStartMs / visibleRangeMs) * 100;
- const blockWidth = (blockDurationMs / visibleRangeMs) * 100;
+ const lastBlock = visibleBlocks[visibleBlocks.length - 1];
+ if (lastBlock && lastBlock.endTime.getTime() < timeRange.end.getTime()) {
+ visibleBlocks.push({
+ appName: "gap",
+ windowName: "No Activity",
+ startTime: lastBlock.endTime,
+ endTime: timeRange.end,
+ color: "transparent",
+ isGap: true,
+ });
+ }
- if (blockWidth < 0.01) return null; // Skip tiny blocks
+ return visibleBlocks;
+ }, [
+ sortedFrames, // Use sorted frames instead of raw frames
+ timeRange.start, // Use timestamp instead of Date object
+ timeRange.end,
+ getAppColor,
+ ]);
+
+ // Add selection state
+ const [isDragging, setIsDragging] = useState(false);
+ const [selectionStart, setSelectionStart] = useState<number | null>(null);
+ const [selectionEnd, setSelectionEnd] = useState<number | null>(null);
+ const containerRef = useRef<HTMLDivElement>(null);
+
+ // Add mouse handlers
+ const handleMouseDown = (e: React.MouseEvent) => {
+ const element = document.elementFromPoint(e.clientX, e.clientY);
+ const blockIndex = element?.getAttribute("data-block-index");
+ if (blockIndex) {
+ const index = parseInt(blockIndex);
+ setSelectionStart(index);
+ setSelectionEnd(index);
+ setSelectionRange({
+ start: blocks[index].startTime,
+ end: blocks[index].endTime,
+ });
+ setIsDragging(true);
+ }
+ };
+
+ // Add debouncing to mouse move handler
+ const handleMouseMove = useMemo(
+ () =>
+ debounce((e: React.MouseEvent) => {
+ if (!isDragging || selectionStart === null) return;
+ const element = document.elementFromPoint(e.clientX, e.clientY);
+ const blockIndex = element?.getAttribute("data-block-index");
+ if (blockIndex) {
+ setSelectionEnd(parseInt(blockIndex));
+ setSelectionRange({
+ start: blocks[selectionStart].startTime,
+ end: blocks[parseInt(blockIndex)].endTime,
+ });
+ }
+ }, 16), // ~60fps
+ [isDragging, selectionStart]
+ );
+
+ const handleMouseUp = () => {
+ setIsDragging(false);
+ };
+
+ // Calculate selection bounds only when needed
+ const selectionBounds = useMemo(() => {
+ if (selectionStart === null || selectionEnd === null) return null;
+
+ const start = Math.min(selectionStart, selectionEnd);
+ const end = Math.max(selectionStart, selectionEnd);
+
+ return {
+ left:
+ ((blocks[start].startTime.getTime() - timeRange.start.getTime()) /
+ (timeRange.end.getTime() - timeRange.start.getTime())) *
+ 100,
+ width:
+ ((blocks[end].endTime.getTime() - blocks[start].startTime.getTime()) /
+ (timeRange.end.getTime() - timeRange.start.getTime())) *
+ 100,
+ };
+ }, [selectionStart, selectionEnd, blocks, timeRange]);
+
+ return (
+ <div
+ ref={containerRef}
+ className="absolute inset-0 flex flex-col"
+ onMouseDown={handleMouseDown}
+ onMouseUp={handleMouseUp}
+ onMouseMove={handleMouseMove}
+ style={{ userSelect: "none" }}
+ >
+ {/* Regular blocks */}
+ {blocks.map((block, index) => {
+ const blockStart =
+ ((block.startTime.getTime() - timeRange.start.getTime()) /
+ (timeRange.end.getTime() - timeRange.start.getTime())) *
+ 100;
+ const blockWidth =
+ ((block.endTime.getTime() - block.startTime.getTime()) /
+ (timeRange.end.getTime() - timeRange.start.getTime())) *
+ 100;
return (
<div
key={`${block.appName}-${index}`}
- className="absolute top-0 bottom-0 opacity-50 hover:opacity-80 transition-opacity z-10"
+ data-block-index={index}
+ className={`absolute top-0 bottom-0 transition-opacity z-10 ${
+ block.isGap
+ ? "hover:bg-gray-200 dark:hover:bg-gray-700 opacity-0 hover:opacity-30"
+ : "opacity-50 hover:opacity-80"
+ }`}
style={{
- left: `${blockStart}%`,
- width: `${blockWidth}%`,
+ transform: `translateX(${blockStart}%) scaleX(${
+ blockWidth / 100
+ })`,
+ transformOrigin: "left",
+ width: "100%",
backgroundColor: block.color,
- willChange: "transform",
}}
title={`${block.appName}\n${
block.windowName
@@ -129,6 +254,18 @@ export function TimelineBlocks({ frames, timeRange }: TimelineBlocksProps) {
/>
);
})}
+
+ {/* Selection overlay */}
+ {selectionBounds && (
+ <div
+ className="absolute top-0 bottom-0 bg-black/20 dark:bg-white/20 z-20"
+ style={{
+ left: `${selectionBounds.left}%`,
+ width: `${selectionBounds.width}%`,
+ willChange: "transform",
+ }}
+ />
+ )}
</div>
);
}
diff --git a/screenpipe-app-tauri/components/timeline/timeline-dock.tsx b/screenpipe-app-tauri/components/timeline/timeline-dock.tsx
index 3ec6e4db2..bb9e811ea 100644
--- a/screenpipe-app-tauri/components/timeline/timeline-dock.tsx
+++ b/screenpipe-app-tauri/components/timeline/timeline-dock.tsx
@@ -320,7 +320,7 @@ export function TimelineIconsSection({
}, [processedBlocks, loadAppIcon]);
return (
- <div className="absolute -top-12 inset-x-0 pointer-events-none h-8">
+ <div className="absolute -top-8 inset-x-0 pointer-events-none h-8">
{processedBlocks.map((block, i) => (
<div
key={`${block.appName}-${i}`}
diff --git a/screenpipe-app-tauri/lib/hooks/use-timeline-selection.tsx b/screenpipe-app-tauri/lib/hooks/use-timeline-selection.tsx
new file mode 100644
index 000000000..84918fcad
--- /dev/null
+++ b/screenpipe-app-tauri/lib/hooks/use-timeline-selection.tsx
@@ -0,0 +1,33 @@
+import { createContext, useContext, ReactNode, useState } from "react";
+
+interface TimelineContextType {
+ selectionRange: { start: Date; end: Date } | null;
+ setSelectionRange: (range: { start: Date; end: Date } | null) => void;
+}
+
+const TimelineContext = createContext<TimelineContextType | undefined>(
+ undefined
+);
+
+export function TimelineProvider({ children }: { children: ReactNode }) {
+ const [selectionRange, setSelectionRange] = useState<{
+ start: Date;
+ end: Date;
+ } | null>(null);
+
+ return (
+ <TimelineContext.Provider value={{ selectionRange, setSelectionRange }}>
+ {children}
+ </TimelineContext.Provider>
+ );
+}
+
+export function useTimelineSelection() {
+ const context = useContext(TimelineContext);
+ if (!context) {
+ throw new Error(
+ "useTimelineSelection must be used within a TimelineProvider"
+ );
+ }
+ return context;
+}