YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
feat: rewind keyword search (#1330)
shaik-zeeshan67f624b30686
diff --git a/pipes/rewind/bun.lockb b/pipes/rewind/bun.lockbindex 613e774a4..2ab027e81 100755Binary files a/pipes/rewind/bun.lockb and b/pipes/rewind/bun.lockb differdiff --git a/pipes/rewind/package.json b/pipes/rewind/package.jsonindex 7055e9b0a..893f2e91a 100644--- a/pipes/rewind/package.json+++ b/pipes/rewind/package.json@@ -10,16 +10,16 @@},"dependencies": {"@radix-ui/react-accordion": "^1.2.2",- "@radix-ui/react-checkbox": "^1.1.3",- "@radix-ui/react-dialog": "^1.1.3",- "@radix-ui/react-label": "^2.1.1",- "@radix-ui/react-popover": "^1.1.3",+ "@radix-ui/react-checkbox": "^1.1.4",+ "@radix-ui/react-dialog": "^1.1.6",+ "@radix-ui/react-label": "^2.1.2",+ "@radix-ui/react-popover": "^1.1.6","@radix-ui/react-progress": "^1.1.1","@radix-ui/react-scroll-area": "^1.2.2","@radix-ui/react-select": "^2.1.3","@radix-ui/react-separator": "^1.1.1","@radix-ui/react-slider": "^1.2.2",- "@radix-ui/react-slot": "^1.1.1",+ "@radix-ui/react-slot": "^1.1.2","@radix-ui/react-switch": "^1.1.2","@radix-ui/react-toast": "^1.2.3","@radix-ui/react-tooltip": "^1.1.5",@@ -33,17 +33,18 @@"ai": "^4.0.18","class-variance-authority": "^0.7.1","clsx": "^2.1.1",- "cmdk": "1.0.0",+ "cmdk": "^1.0.4","date-fns": "^4.1.0","framer-motion": "^11.14.4","install": "^0.13.0","js-levenshtein": "^1.1.6","localforage": "^1.10.0","lodash": "^4.17.21",- "lucide-react": "^0.468.0",+ "lucide-react": "^0.475.0","magic-ui": "^0.1.0","next": "15.1.0","npm": "^10.9.2",+ "nuqs": "^2.3.2","openai": "^4.76.3","react": "^19.0.0","react-day-picker": "8.10.1",@@ -52,6 +53,7 @@"react-syntax-highlighter": "^15.6.1","remark-gfm": "^4.0.0","remark-math": "^6.0.0",+ "stopword": "^3.1.4","tailwind-merge": "^2.5.5","tailwindcss-animate": "^1.0.7","zustand": "^5.0.3"@@ -61,6 +63,7 @@"@types/node": "^22.10.2","@types/react": "^19","@types/react-dom": "^19",+ "@types/stopword": "^2.0.3","autoprefixer": "^10.4.20","eslint": "^9.19.0","postcss": "^8.4.49",diff --git a/pipes/rewind/src/app/api/settings/route.ts b/pipes/rewind/src/app/api/settings/route.tsindex f15de9b31..b78a76867 100644--- a/pipes/rewind/src/app/api/settings/route.ts+++ b/pipes/rewind/src/app/api/settings/route.ts@@ -1,60 +1,59 @@// app/api/settings/route.tsimport { pipe } from "@screenpipe/js";import { NextResponse } from "next/server";-import type { Settings } from "@screenpipe/js";import { getDefaultSettings } from "@screenpipe/browser";// Force Node.js runtimeexport const runtime = "nodejs"; // Add this lineexport const dynamic = "force-dynamic";export async function GET() {- const defaultSettings = getDefaultSettings();- try {- const settingsManager = pipe.settings;- if (!settingsManager) {- throw new Error("settingsManager not found");- }- const rawSettings = await settingsManager.getAll();- return NextResponse.json(rawSettings);- } catch (error) {- console.error("failed to get settings:", error);- return NextResponse.json(defaultSettings);- }+ const defaultSettings = getDefaultSettings();+ try {+ const settingsManager = pipe.settings;+ if (!settingsManager) {+ throw new Error("settingsManager not found");+ }+ const rawSettings = await settingsManager.getAll();+ return NextResponse.json(rawSettings);+ } catch (error) {+ console.error("failed to get settings:", error);+ return NextResponse.json(defaultSettings);+ }}export async function PUT(request: Request) {- try {- const settingsManager = pipe.settings;- if (!settingsManager) {- throw new Error("settingsManager not found");- }+ try {+ const settingsManager = pipe.settings;+ if (!settingsManager) {+ throw new Error("settingsManager not found");+ }- const body = await request.json();- const { key, value, isPartialUpdate, reset } = body;+ const body = await request.json();+ const { key, value, isPartialUpdate, reset } = body;- if (reset) {- if (key) {- await settingsManager.resetKey(key);- } else {- await settingsManager.reset();- }- return NextResponse.json({ success: true });- }+ if (reset) {+ if (key) {+ await settingsManager.resetKey(key);+ } else {+ await settingsManager.reset();+ }+ return NextResponse.json({ success: true });+ }- if (isPartialUpdate) {- const serializedSettings = JSON.parse(JSON.stringify(value));- await settingsManager.update(serializedSettings);- } else {- const serializedValue = JSON.parse(JSON.stringify(value));- await settingsManager.set(key, serializedValue);- }+ if (isPartialUpdate) {+ const serializedSettings = JSON.parse(JSON.stringify(value));+ await settingsManager.update(serializedSettings);+ } else {+ const serializedValue = JSON.parse(JSON.stringify(value));+ await settingsManager.set(key, serializedValue);+ }- return NextResponse.json({ success: true });- } catch (error) {- console.error("failed to update settings:", error);- return NextResponse.json(- { error: "failed to update settings" },- { status: 500 }- );- }+ return NextResponse.json({ success: true });+ } catch (error) {+ console.error("failed to update settings:", error);+ return NextResponse.json(+ { error: "failed to update settings" },+ { status: 500 },+ );+ }}diff --git a/pipes/rewind/src/app/layout.tsx b/pipes/rewind/src/app/layout.tsxindex b04d3a226..e87afd870 100644--- a/pipes/rewind/src/app/layout.tsx+++ b/pipes/rewind/src/app/layout.tsx@@ -1,6 +1,10 @@import type { Metadata } from "next";import { Geist, Geist_Mono } from "next/font/google";import "./globals.css";+import { SearchCommand } from "@/components/search-command";+import { NuqsAdapter } from "nuqs/adapters/next/app";+import { getScreenpipeAppSettings } from "@/lib/actions/get-screenpipe-app-settings";+import { SettingsProvider } from "@/components/settings-provider";const geistSans = Geist({variable: "--font-geist-sans",@@ -26,9 +30,7 @@ export default async function RootLayout({}>) {const checkSettings = async () => {try {- const port = process.env.PORT || 3000;- const response = await fetch(`http://localhost:${port}/api/settings`);- const settings = await response.json();+ const settings = await getScreenpipeAppSettings();return settings.enableFrameCache;} catch (error) {@@ -44,19 +46,26 @@ export default async function RootLayout({<bodyclassName={`${geistSans.variable} ${geistMono.variable} antialiased`}>- {!enabled ? (- <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>+ <SettingsProvider>+ {!enabled ? (+ <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>- ) : (- <>{children}</>- )}+ ) : (+ <>+ <NuqsAdapter>+ <SearchCommand />+ {children}+ </NuqsAdapter>+ </>+ )}+ </SettingsProvider></body></html>);diff --git a/pipes/rewind/src/app/page.tsx b/pipes/rewind/src/app/page.tsxindex 2e4b9b56a..feb6fa1f6 100644--- a/pipes/rewind/src/app/page.tsx+++ b/pipes/rewind/src/app/page.tsx@@ -1,16 +1,12 @@"use client";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";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";-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 { addDays, isAfter, isSameDay, subDays } from "date-fns";import { getStartDate } from "@/lib/actions/get-start-date";import { useTimelineData } from "@/lib/hooks/use-timeline-data";@@ -18,6 +14,7 @@ import { useCurrentFrame } from "@/lib/hooks/use-current-frame";import { TimelineSlider } from "@/components/timeline/timeline";import { useTimelineStore } from "@/lib/hooks/use-timeline-store";import { hasFramesForDate } from "@/lib/actions/has-frames-date";+import { CommandShortcut } from "@/components/ui/command";export interface StreamTimeSeriesResponse {timestamp: string;@@ -265,11 +262,16 @@ export default function Timeline() {if (!hasDateBeenFetched(newDate)) {setCurrentFrame(null);const frameTimeStamp = new Date(newDate);- if (frameTimeStamp.getDate() === new Date(currentDate).getDate()) {+ console.log(+ frameTimeStamp.getDate() === new Date(currentDate).getDate(),+ startAndEndDates.start.getDate(),+ newDate.getDate(),+ );+ if (isSameDay(frameTimeStamp, new Date(currentDate))) {return;}- if (isAfter(startAndEndDates.start.getDate(), newDate.getDate())) {+ if (isAfter(startAndEndDates.start, newDate)) {return;}@@ -342,6 +344,10 @@ export default function Timeline() {onResultSelect={animateToIndex}onSearchResults={setSearchResults}/> */}+ <div>+ <CommandShortcut>⌘K</CommandShortcut>{" "}+ <span className="text-xs text-muted-foreground">to search</span>+ </div></div></div>@@ -393,7 +399,6 @@ export default function Timeline() {)}{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"diff --git a/pipes/rewind/src/app/search/page.tsx b/pipes/rewind/src/app/search/page.tsxnew file mode 100644index 000000000..721830599--- /dev/null+++ b/pipes/rewind/src/app/search/page.tsx@@ -0,0 +1,134 @@+"use client";++import { DatePickerWithRange } from "@/components/date-range-picker";+import { ImageGrid, MainImage } from "@/components/image-card";+import { SearchBar } from "@/components/search-bar";+import { Button } from "@/components/ui/button";+import { useDebounce } from "@/lib/hooks/use-debounce";+import { useKeywordSearchStore } from "@/lib/hooks/use-keyword-search-store";+import { endOfDay, startOfDay } from "date-fns";+import { useCallback, useEffect, useRef } from "react";+import { parser } from "@/lib/keyword-parser";+import { CurrentFrame } from "@/components/current-frame";+import { useKeywordParams } from "@/lib/hooks/use-keyword-params";+import { AppSelect } from "@/components/search-command";+import { ArrowLeft } from "lucide-react";++export default function Page() {+ const [querys, setQuerys] = useKeywordParams();+ const debounceQuerys = useDebounce(querys, 300);+ const {+ searchKeywords,+ isSearching,+ searchResults,+ currentResultIndex,+ setCurrentResultIndex,+ } = useKeywordSearchStore();+ const pageRef = useRef<HTMLDivElement>(null);++ const handleSearch = useCallback(+ async (+ query: string,+ start: Date | undefined,+ end: Date | undefined,+ app_names: string[] | undefined,+ ) => {+ await searchKeywords(query, {+ limit: 20,+ offset: 0,+ start_time: start,+ end_time: end,+ app_names,+ });+ },+ [searchResults],+ );++ useEffect(() => {+ if (!debounceQuerys.query || debounceQuerys.query.length === 0) {+ setCurrentResultIndex(-1);+ return;+ }++ const keywords = parser.parse(debounceQuerys.query);+ if (keywords.keywords.length === 0) return;++ console.log(keywords.keywords);++ handleSearch(+ keywords.keywords.join(" "),+ debounceQuerys.start_time ?? undefined,+ debounceQuerys.end_time ?? undefined,+ debounceQuerys.apps?.length ? debounceQuerys.apps : undefined,+ );+ }, [debounceQuerys]);++ useEffect(() => {+ console.log(currentResultIndex);+ }, [currentResultIndex]);++ return (+ <div+ ref={pageRef}+ className="mx-auto flex flex-col justify-between space-y-4 animate-fade-in p-4 min-h-screen overflow-hidden"+ >+ <div className="space-y-4 ">+ <div className="flex items-center gap-4 justify-center">+ <Button variant={"link"} asChild>+ <a href={"/"}>+ <ArrowLeft />+ Go Back+ </a>+ </Button>+ <div className="grid grid-cols-3 gap-4 items-center h-10">+ <SearchBar+ search={querys.query}+ onSearchChange={(query) => {+ setQuerys((prev) => ({+ ...prev,+ query,+ }));+ }}+ />+ <DatePickerWithRange+ start_time={querys.start_time}+ end_time={querys.end_time}+ setDateRange={(dates) => {+ setQuerys((prev) => ({+ ...prev,+ start_time: dates?.from ? startOfDay(dates?.from) : null,+ end_time: dates?.to ? endOfDay(dates?.to) : null,+ }));+ }}+ />+ <AppSelect+ apps={querys.apps ?? []}+ setApps={(values) => {+ setQuerys((prev) => ({+ ...prev,+ apps: values,+ }));+ }}+ />+ </div>+ </div>+ <CurrentFrame />+ </div>+ {!querys.query && (+ <div className="h-64 w-96 flex mx-auto items-center justify-center">+ <p className="text-sm text-gray-500">+ Please provide query for searching+ </p>+ </div>+ )}++ {querys.query ? (+ <div className="h-64 flex items-end">+ <ImageGrid searchResult={searchResults} pageRef={pageRef} />+ </div>+ ) : (+ <div></div>+ )}+ </div>+ );+}diff --git a/pipes/rewind/src/components/ai-frame-response.tsx b/pipes/rewind/src/components/ai-frame-response.tsxnew file mode 100644index 000000000..2d6aa48a4--- /dev/null+++ b/pipes/rewind/src/components/ai-frame-response.tsx@@ -0,0 +1,145 @@+import { useDebounce } from "@/lib/hooks/use-debounce";+import { useKeywordSearchStore } from "@/lib/hooks/use-keyword-search-store";+import { useSettings } from "@/lib/hooks/use-settings";+import OpenAI from "openai";+import { zodResponseFormat } from "openai/helpers/zod.mjs";+import { z } from "zod";+import { useCallback, useEffect, useState } from "react";+import { Button } from "./ui/button";++interface FrameAIResponse {+ explain: string;+ links: string[];+}++export const AIFrameResponse = () => {+ const { settings } = useSettings();+ const { currentResultIndex, searchResults } = useKeywordSearchStore();+ const debouncedResultIndex = useDebounce(currentResultIndex, 500);+ const [aiContent, setAiContent] = useState<FrameAIResponse | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const generateFrameResponse = useCallback(async () => {+ try {+ if (aiContent !== null) return;+ const currentFrame = searchResults[debouncedResultIndex];+ if (settings?.aiModel?.length === 0) {+ return;+ }+ if (!currentFrame) return;++ const frame = {+ frame_id: currentFrame.frame_id,+ timestamp: currentFrame.timestamp,+ window_name: currentFrame.window_name,+ app_name: currentFrame.app_name,+ text: currentFrame.text,+ };++ setIsLoading(true);++ // Initialize OpenAI+ const openai = new OpenAI({+ apiKey:+ settings?.aiProviderType === "screenpipe-cloud"+ ? settings?.user?.token+ : settings?.openaiApiKey,+ baseURL: settings?.aiUrl,+ dangerouslyAllowBrowser: true,+ });++ const prompt = `${JSON.stringify(frame)}`;++ // Generate suggestions using OpenAI+ const response = await openai.chat.completions.create({+ model: settings?.aiModel || "",+ messages: [+ {+ role: "system",+ content: `+You are an advanced text analyzer. You will be given text and metadata extracted from an image. Your task is to determine its content, identify any website references, and return structured output.++### **Guidelines:**+- **State facts directly**—do not say "the content is about"; simply state what it is.+- **Use present tense**—avoid words like *could be* or *might be*.+- **Address the user as "you"**—never refer to them as "user."+- **Identify social media content**—if the text indicates a social media platform, return the platform's links. If a person's ID is present, generate a link to their profile.++### **Input Format Example:**+{+ "frame_id": <frame_id>,+ "timestamp": <date and time of frame>,+ "app_name": <app_name>,+ "window_name": <window_name>,+ "text": <ocr content of frame>+}+`,+ },+ {+ role: "user",+ content: prompt,+ },+ ],+ response_format: zodResponseFormat(+ z.object({+ explain: z+ .string()+ .describe(+ "State the content and why you are seeing it, inferred from the text (max 30 words)",+ ),+ links: z+ .array(z.string())+ .describe(+ "Extracted web links or relevant social media profiles",+ ),+ }),+ "frame_explain_response",+ ),+ });++ const content = response.choices[0]?.message?.content;++ console.log(JSON.parse(content ?? "{}"));+ setAiContent(JSON.parse(content ?? "{}"));+ } catch (err) {+ setError(+ err instanceof Error ? err.message : "failed to get ai response",+ );+ } finally {+ setIsLoading(false);+ }+ }, [debouncedResultIndex, settings]);++ useEffect(() => {+ generateFrameResponse();+ }, [generateFrameResponse]);++ return (+ <div className="text-neutral-600 w-full break-words">+ {isLoading ? (+ "Loading"+ ) : error ? (+ error+ ) : (+ <div className="space-y-2">+ <div>{aiContent?.explain}</div>+ <div className="space-y-2">+ {aiContent?.links.map((link, i) => {+ return (+ <Button variant={"link"} key={i} asChild>+ <a href={link} target="_blank">+ <img+ src={`https://www.google.com/s2/favicons?domain=${link}&sz=128`}+ className="object-cover h-8 w-8"+ />+ </a>+ </Button>+ );+ })}+ </div>+ </div>+ )}+ </div>+ );+};diff --git a/pipes/rewind/src/components/chat-message.tsx b/pipes/rewind/src/components/chat-message.tsxindex 2dee23299..9b08f3d11 100644--- a/pipes/rewind/src/components/chat-message.tsx+++ b/pipes/rewind/src/components/chat-message.tsx@@ -11,101 +11,101 @@ import { useSettings } from "@/lib/hooks/use-settings";import { VideoComponent } from "./video";export interface ChatMessageProps {- message: Message;+ message: Message;}export function ChatMessage({ message, ...props }: ChatMessageProps) {- const { settings } = useSettings();+ const { settings } = useSettings();- const hasMP4File = (content: string) =>- content.trim().toLowerCase().includes(".mp4");+ const hasMP4File = (content: string) =>+ content.trim().toLowerCase().includes(".mp4");- if (!message?.content?.trim()) {- return null;- }+ if (!message?.content?.trim()) {+ return null;+ }- return (- <div- className={cn("group relative mb-4 flex items-start w-full")}- {...props}- >- <div- className={cn(- "flex size-8 shrink-0 select-none items-center justify-center rounded-md border shadow",- message.role === "user"- ? "bg-background"- : "bg-primary text-primary-foreground"- )}- >- {message.role === "user" ? (- <IconUser />- ) : settings.aiUrl.includes("openai") ||- settings.aiUrl.includes("worker") ? (- <IconOpenAI />- ) : (- <>🦙</>- )}- </div>- <div className="flex-1 px-1 ml-4 space-y-2 overflow-hidden w-[96em]">- <MemoizedReactMarkdown- className="prose break-words dark:prose-invert prose-p:leading-relaxed prose-pre:p-0 w-full"- remarkPlugins={[remarkGfm, remarkMath]}- components={{- p({ children }) {- return <p className="mb-2 last:mb-0">{children}</p>;- },- a({ node, href, children, ...props }) {- const isMP4Link = href?.toLowerCase().includes(".mp4");+ return (+ <div+ className={cn("group relative mb-4 flex items-start w-full")}+ {...props}+ >+ <div+ className={cn(+ "flex size-8 shrink-0 select-none items-center justify-center rounded-md border shadow",+ message.role === "user"+ ? "bg-background"+ : "bg-primary text-primary-foreground",+ )}+ >+ {message.role === "user" ? (+ <IconUser />+ ) : settings?.aiUrl?.includes("openai") ||+ settings?.aiUrl?.includes("worker") ? (+ <IconOpenAI />+ ) : (+ <>🦙</>+ )}+ </div>+ <div className="flex-1 px-1 ml-4 space-y-2 overflow-hidden w-[96em]">+ <MemoizedReactMarkdown+ className="prose break-words dark:prose-invert prose-p:leading-relaxed prose-pre:p-0 w-full"+ remarkPlugins={[remarkGfm, remarkMath]}+ components={{+ p({ children }) {+ return <p className="mb-2 last:mb-0">{children}</p>;+ },+ a({ node, href, children, ...props }) {+ const isMP4Link = href?.toLowerCase().includes(".mp4");- if (isMP4Link && href) {- return <VideoComponent filePath={href} />;- }- return (- <a- href={href}- target="_blank"- rel="noopener noreferrer"- {...props}- >- {children}- </a>- );- },- code({ node, className, children, ...props }) {- const content = String(children).replace(/\n$/, "");- const match = /language-(\w+)/.exec(className || "");+ if (isMP4Link && href) {+ return <VideoComponent filePath={href} />;+ }+ return (+ <a+ href={href}+ target="_blank"+ rel="noopener noreferrer"+ {...props}+ >+ {children}+ </a>+ );+ },+ code({ node, className, children, ...props }) {+ const content = String(children).replace(/\n$/, "");+ const match = /language-(\w+)/.exec(className || "");- const isMP4File = hasMP4File(content);+ const isMP4File = hasMP4File(content);- if (isMP4File || !match) {- if (isMP4File) {- return <VideoComponent filePath={content.trim()} />;- }- return (- <code- className="px-1 py-0.5 rounded-sm font-mono text-sm"- {...props}- >- {content}- </code>- );- }+ if (isMP4File || !match) {+ if (isMP4File) {+ return <VideoComponent filePath={content.trim()} />;+ }+ return (+ <code+ className="px-1 py-0.5 rounded-sm font-mono text-sm"+ {...props}+ >+ {content}+ </code>+ );+ }- return (- <CodeBlock- key={Math.random()}- language={(match && match[1]) || ""}- value={content}- {...props}- />- );- },- }}- >- {message.content}- </MemoizedReactMarkdown>- <ChatMessageActions message={message} />- </div>- </div>- );+ return (+ <CodeBlock+ key={Math.random()}+ language={(match && match[1]) || ""}+ value={content}+ {...props}+ />+ );+ },+ }}+ >+ {message.content}+ </MemoizedReactMarkdown>+ <ChatMessageActions message={message} />+ </div>+ </div>+ );}diff --git a/pipes/rewind/src/components/current-frame.tsx b/pipes/rewind/src/components/current-frame.tsxnew file mode 100644index 000000000..a752de6bf--- /dev/null+++ b/pipes/rewind/src/components/current-frame.tsx@@ -0,0 +1,41 @@+import { MainImage } from "./image-card";+import { cn } from "@/lib/utils";+import { useKeywordSearchStore } from "@/lib/hooks/use-keyword-search-store";++function isValidURL(url: string) {+ try {+ new URL(url);+ return true;+ } catch (error) {+ return false;+ }+}++export const CurrentFrame = () => {+ const { currentResultIndex, searchResults } = useKeywordSearchStore();++ const currentFrame = searchResults[currentResultIndex];++ return (+ <div+ className={cn(+ "grid md:gap-4 gap-y-4 w-4/5 mx-auto h-auto max-h-[60vh] max-w-[50vw] overflow-hidden",+ )}+ >+ <div className={cn("relative group w-full")}>+ <MainImage />+ {currentFrame?.url && isValidURL(currentFrame.url) && (+ <a+ className={cn(+ "absolute text-xs rounded bottom-4 right-4 bg-muted p-1 font-mono opacity-80 group-hover:opacity-100 transition-all duration-200",+ )}+ target="_blank"+ href={currentFrame.url}+ >+ Open URL+ </a>+ )}+ </div>+ </div>+ );+};diff --git a/pipes/rewind/src/components/custom-dialog-content.tsx b/pipes/rewind/src/components/custom-dialog-content.tsxnew file mode 100644index 000000000..842baa5b4--- /dev/null+++ b/pipes/rewind/src/components/custom-dialog-content.tsx@@ -0,0 +1,31 @@+import * as React from "react";+import * as DialogPrimitive from "@radix-ui/react-dialog";+import { cn } from "@/lib/utils";+import { DialogOverlay, DialogPortal } from "./ui/dialog";++export const CustomDialogContent = React.forwardRef<+ React.ElementRef<typeof DialogPrimitive.Content>,+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & {+ customClose?: React.ReactNode;+ }+>(({ className, children, customClose, ...props }, ref) => (+ <DialogPortal>+ <DialogOverlay />+ <DialogPrimitive.Content+ ref={ref}+ className={cn(+ "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",+ className,+ )}+ {...props}+ >+ {children}+ <DialogPrimitive.Close+ asChild+ className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground"+ >+ {customClose}+ </DialogPrimitive.Close>+ </DialogPrimitive.Content>+ </DialogPortal>+));diff --git a/pipes/rewind/src/components/date-range-picker.tsx b/pipes/rewind/src/components/date-range-picker.tsxnew file mode 100644index 000000000..074424536--- /dev/null+++ b/pipes/rewind/src/components/date-range-picker.tsx@@ -0,0 +1,77 @@+"use client";++import * as React from "react";+import { format } from "date-fns";+import { CalendarIcon } from "lucide-react";+import { SelectRangeEventHandler } from "react-day-picker";++import { cn } from "@/lib/utils";+import { Button } from "@/components/ui/button";+import { Calendar } from "@/components/ui/calendar";+import {+ Popover,+ PopoverContentInDialog as PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";++export function DatePickerWithRange({+ className,+ start_time,+ end_time,+ disabled,+ setDateRange,+}: React.HTMLAttributes<HTMLDivElement> & {+ start_time: Date | null;+ end_time: Date | null;+ setDateRange: SelectRangeEventHandler;+ disabled?: boolean | undefined;+}) {+ return (+ <div className={cn("grid gap-2 w-full h-full", className)}>+ <Popover>+ <PopoverTrigger asChild>+ <Button+ id="date"+ disabled={disabled}+ variant={"outline"}+ className={cn(+ "w-full h-full justify-start text-left font-normal",+ !start_time && "text-muted-foreground",+ )}+ >+ <CalendarIcon />+ {start_time ? (+ end_time ? (+ <>+ {format(start_time, "LLL dd, y")} -{" "}+ {format(end_time, "LLL dd, y")}+ </>+ ) : (+ format(start_time, "LLL dd, y")+ )+ ) : (+ <span>Filter by Date</span>+ )}+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-auto p-0" align="start">+ <Calendar+ initialFocus+ mode="range"+ defaultMonth={start_time ?? undefined}+ selected={{+ from: start_time ?? undefined,+ to: end_time ?? undefined,+ }}+ onSelect={setDateRange}+ numberOfMonths={2}+ disabled={{+ after: new Date(),+ }}+ toMonth={new Date()}+ />+ </PopoverContent>+ </Popover>+ </div>+ );+}diff --git a/pipes/rewind/src/components/image-card.tsx b/pipes/rewind/src/components/image-card.tsxnew file mode 100644index 000000000..7511f7b1d--- /dev/null+++ b/pipes/rewind/src/components/image-card.tsx@@ -0,0 +1,306 @@+import { format } from "date-fns";+import { useEffect, useRef, useMemo, useState, RefObject } from "react";+import { SearchMatch } from "@/lib/hooks/use-keyword-search-store";+import { useKeywordSearchStore } from "@/lib/hooks/use-keyword-search-store";+import { cn } from "@/lib/utils";+import { throttle } from "lodash";+import { Loader2 } from "lucide-react";+import { useKeywordParams } from "@/lib/hooks/use-keyword-params";++export const ImageGrid = ({+ searchResult,+ pageRef,+}: {+ searchResult: SearchMatch[];+ pageRef: RefObject<HTMLDivElement | null>;+}) => {+ const containerRef = useRef<HTMLDivElement>(null);+ const { setCurrentResultIndex, currentResultIndex, searchKeywords } =+ useKeywordSearchStore();+ const [{ start_time, end_time, query, apps }] = useKeywordParams();+ const { searchResults, isSearching } = useKeywordSearchStore();++ const checkScrollAndFetch = useMemo(+ () =>+ throttle(() => {+ const container = containerRef.current;+ if (!container) return;+ if (searchResults.length === 0) return;++ const scrollPosition = Math.abs(container.scrollLeft);+ const scrollWidth = container.scrollWidth;+ const clientWidth = container.clientWidth;++ const scrollPercentage = scrollPosition / (scrollWidth - clientWidth);++ if (scrollPercentage > 0.6) {+ searchKeywords(query ?? "", {+ offset: searchResult.length,+ limit: 20,+ ...(start_time && { start_time }),+ ...(end_time && { end_time }),+ ...(apps?.length && { app_names: apps }),+ });+ }+ }, 400),+ [searchResult.length, searchKeywords, query, start_time, end_time, apps],+ );++ useEffect(() => {+ const container = containerRef.current;+ if (container) {+ container.addEventListener("scroll", checkScrollAndFetch);+ }++ return () => {+ if (container) {+ container.removeEventListener("scroll", checkScrollAndFetch);+ }+ };+ }, [checkScrollAndFetch]);++ const handleScroll = useMemo(+ () =>+ throttle(+ (e: WheelEvent) => {+ const isWithinAiPanel =+ e.target instanceof Node &&+ document.getElementById("ai-response")?.contains(e.target);++ if (isWithinAiPanel) return;++ e.preventDefault();+ e.stopPropagation();++ const scrollIntensity = Math.abs(e.deltaY);+ const direction = -Math.sign(e.deltaY);+ const limitIndexChange = 5;++ const indexChange =+ direction *+ Math.min(+ limitIndexChange,+ Math.ceil(Math.pow(scrollIntensity / 50, 1.5)),+ );++ requestAnimationFrame(() => {+ const newIndex = Math.min(+ Math.max(0, Math.floor(currentResultIndex + indexChange)),+ searchResult.length - 1,+ );+ setCurrentResultIndex(newIndex);+ });+ },+ 16,+ { leading: true, trailing: false },+ ),+ [searchResult.length, currentResultIndex, setCurrentResultIndex],+ );++ useEffect(() => {+ const preventScroll = (e: WheelEvent) => {+ e.preventDefault();+ };++ document.addEventListener("wheel", preventScroll, { passive: false });+ return () => document.removeEventListener("wheel", preventScroll);+ }, []);++ useEffect(() => {+ const container = containerRef.current;+ if (container && pageRef.current) {+ pageRef.current.addEventListener("wheel", handleScroll, {+ passive: false,+ });+ }++ return () => {+ if (container && pageRef.current) {+ pageRef.current.removeEventListener("wheel", handleScroll);+ }+ };+ }, [handleScroll]);++ useEffect(() => {+ const container = containerRef.current;+ if (!container || !searchResult[currentResultIndex]) return;++ const currentTimestamp = searchResult[currentResultIndex].timestamp;+ const currentElement = container.querySelector(+ `[data-timestamp="${currentTimestamp}"]`,+ );++ if (!currentElement) return;++ requestAnimationFrame(() => {+ const containerWidth = container.clientWidth;+ const elementWidth = (currentElement as HTMLElement).offsetWidth;+ const elementOffsetRight =+ container.scrollWidth -+ ((currentElement as HTMLElement).offsetLeft + elementWidth);++ const centerPosition =+ elementOffsetRight - (containerWidth - elementWidth) / 2;++ container.scrollTo({+ left: container.scrollWidth - containerWidth - centerPosition,+ behavior: "smooth",+ });+ });+ }, [currentResultIndex, searchResult]);++ return (+ <div className="relative w-full h-full">+ <div+ ref={containerRef}+ className="sticky inset-0 w-full overflow-x-auto overflow-y-hidden select-none scrollbar-hide"+ style={{ direction: "rtl" }}+ >+ <div className="inline-flex min-w-full px-[50vw]">+ <div className="flex flex-row gap-4 p-8" style={{ direction: "rtl" }}>+ {searchResult.map((result, index) => (+ <div+ key={result.frame_id}+ data-timestamp={result.timestamp}+ className={cn(+ "group flex flex-col shrink-0 w-56 h-full relative overflow-hidden rounded-lg bg-white shadow-sm transition-all duration-300 hover:shadow-md snap-center cursor-pointer",+ currentResultIndex === index && "ring-2 ring-blue-500",+ )}+ onClick={() => setCurrentResultIndex(index)}+ style={{ direction: "ltr" }}+ >+ <div className="aspect-video overflow-hidden flex-1 relative">+ <div className="absolute inset-0 flex items-center justify-center bg-neutral-100">+ <Loader2 className="h-5 w-5 animate-spin text-gray-400" />+ </div>+ <img+ src={`http://localhost:3030/frames/${result.frame_id}`}+ alt={`${result.app_name} - ${result.window_name}`}+ className="h-full w-full object-cover transition-transform duration-300 relative group-hover:scale-105"+ loading="lazy"+ draggable={false}+ onLoad={(e) => {+ (e.target as HTMLImageElement).style.opacity = "1";+ }}+ style={{ opacity: 0 }}+ />+ </div>+ <div className="p-3 space-y-1">+ <p className="text-sm font-medium text-neutral-900 truncate">+ {result.app_name}+ </p>+ <p className="text-xs text-neutral-500 truncate">+ {result.window_name}+ </p>+ <p className="text-xs text-neutral-400">+ {format(new Date(result.timestamp), "PPp")}+ </p>+ </div>+ </div>+ ))}+ </div>+ </div>+ {isSearching ? (+ <div className="h-64 w-96 mx-auto flex items-center justify-center">+ <div className="flex flex-col items-center gap-2">+ <Loader2 className="h-8 w-8 animate-spin text-gray-500" />+ <p className="text-sm text-gray-500">+ Searching through your history...+ </p>+ </div>+ </div>+ ) : searchResults.length === 0 && query ? (+ <div className="h-64 w-96 flex mx-auto items-center justify-center">+ <p className="text-sm text-gray-500">+ No results found for "{query}"+ </p>+ </div>+ ) : null}+ </div>+ </div>+ );+};++interface TextBounds {+ left: number;+ top: number;+ width: number;+ height: number;+}++interface TextPosition {+ text: string;+ confidence: number;+ bounds: TextBounds;+}++export const MainImage = () => {+ const { searchResults, currentResultIndex } = useKeywordSearchStore();+ const imageRef = useRef<HTMLImageElement>(null);+ const containerRef = useRef<HTMLDivElement>(null);+ const [imageRect, setImageRect] = useState<DOMRect | null>(null);++ const currentFrame = searchResults[currentResultIndex];++ useEffect(() => {+ const updateImageRect = () => {+ if (imageRef.current) {+ const rect = imageRef.current.getBoundingClientRect();+ setImageRect(rect);+ }+ };++ updateImageRect();+ const resizeObserver = new ResizeObserver(updateImageRect);+ if (containerRef.current) {+ resizeObserver.observe(containerRef.current);+ }++ window.addEventListener("resize", updateImageRect);+ return () => {+ window.removeEventListener("resize", updateImageRect);+ resizeObserver.disconnect();+ };+ }, [currentFrame]);++ if (!currentFrame) {+ return (+ <div className="relative col-span-3 aspect-video w-full h-full overflow-hidden rounded-lg bg-neutral-100">+ <div className="animate-pulse absolute inset-0 bg-neutral-200" />+ <div className="h-full w-full object-cover opacity-0 transition-opacity duration-300" />+ </div>+ );+ }++ return (+ <div+ ref={containerRef}+ className="relative aspect-auto w-full h-full overflow-hidden rounded-lg bg-neutral-100"+ >+ <div className="absolute inset-0 flex items-center justify-center">+ <Loader2 className="h-8 w-8 animate-spin text-gray-400" />+ </div>+ <div className="relative">+ <img+ ref={imageRef}+ src={`http://localhost:3030/frames/${currentFrame.frame_id}`}+ alt={`${currentFrame.app_name} - ${currentFrame.window_name}`}+ className="h-full w-full object-contain max-h-[75vh]"+ draggable={false}+ onLoad={(e) => {+ (e.target as HTMLImageElement).style.opacity = "1";+ }}+ style={{ opacity: 0 }}+ />+ {imageRect && (+ <div+ className="absolute inset-0 pointer-events-none"+ style={{+ width: imageRect.width,+ }}+ />+ )}+ </div>+ </div>+ );+};diff --git a/pipes/rewind/src/components/scroll-container.tsx b/pipes/rewind/src/components/scroll-container.tsxnew file mode 100644index 000000000..39a2e6271--- /dev/null+++ b/pipes/rewind/src/components/scroll-container.tsx@@ -0,0 +1,54 @@+import React, { forwardRef, useEffect } from "react";+import { cn } from "@/lib/utils";++interface CustomScrollContainerProps+ extends React.HTMLAttributes<HTMLDivElement> {+ children: React.ReactNode;+ className?: string;+ onCustomScroll?: (scrollLeft: number) => void;+}++export const CustomScrollContainer = forwardRef<+ HTMLDivElement,+ CustomScrollContainerProps+>(({ children, className, onCustomScroll, ...props }, ref) => {+ useEffect(() => {+ const container = ref as React.RefObject<HTMLDivElement>;+ if (!container.current) return;++ const handleWheel = (e: WheelEvent) => {+ e.preventDefault();+ if (!container.current) return;++ const scrollAmount = e.deltaY;+ const newScrollLeft = container.current.scrollLeft + scrollAmount;++ container.current.scrollTo({+ left: newScrollLeft,+ behavior: "smooth",+ });++ onCustomScroll?.(newScrollLeft);+ };++ container.current.addEventListener("wheel", handleWheel, {+ passive: false,+ });++ return () => {+ container.current?.removeEventListener("wheel", handleWheel);+ };+ }, [ref, onCustomScroll]);++ return (+ <div+ ref={ref}+ className={cn("snap-x snap-mandatory scroll-smooth", className)}+ {...props}+ >+ {children}+ </div>+ );+});++CustomScrollContainer.displayName = "CustomScrollContainer";diff --git a/pipes/rewind/src/components/search-bar.tsx b/pipes/rewind/src/components/search-bar.tsxnew file mode 100644index 000000000..b59371e71--- /dev/null+++ b/pipes/rewind/src/components/search-bar.tsx@@ -0,0 +1,28 @@+import { Search } from "lucide-react";+import { Input } from "./ui/input";++export const SearchBar = ({+ search,+ onSearchChange,+ disabled,+}: {+ search: string | null;+ onSearchChange: (value: string) => void;+ disabled?: boolean;+}) => {+ return (+ <div className="relative w-full">+ <Input+ type="input"+ placeholder="Search..."+ className="pl-10 h-full bg-white/80 backdrop-blur-sm border border-neutral-200 rounded-lg shadow-sm transition-all duration-200 focus:shadow-md"+ value={search || ""}+ onChange={(e) => {+ onSearchChange(e.target.value);+ }}+ disabled={disabled}+ />+ <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-neutral-400 w-5 h-5" />+ </div>+ );+};diff --git a/pipes/rewind/src/components/search-command.tsx b/pipes/rewind/src/components/search-command.tsxnew file mode 100644index 000000000..c086c6b34--- /dev/null+++ b/pipes/rewind/src/components/search-command.tsx@@ -0,0 +1,188 @@+"use client";++import * as React from "react";++import { useState } from "react";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "./ui/tooltip";+import { MultiSelectCombobox } from "./ui/multi-select-combobox";+import { useSqlAutocomplete } from "@/lib/hooks/use-sql-autocomplete";+import { Dialog, DialogTitle } from "./ui/dialog";+import { Input } from "./ui/input";+import { DatePickerWithRange } from "./date-range-picker";+import { queryParser, QueryParser, querySerializer } from "@/lib/utils";+import { CustomDialogContent } from "./custom-dialog-content";+import { ArrowRight, XIcon } from "lucide-react";+import { useQueryStates } from "nuqs";+import { CommandShortcut } from "./ui/command";++export function SearchCommand() {+ const [open, setOpen] = React.useState(false);++ const [state] = useQueryStates(queryParser);+ const [options, setOptions] = useState<QueryParser>(+ !state+ ? {+ query: null,+ start_time: null,+ end_time: null,+ apps: [],+ }+ : state,+ );++ React.useEffect(() => {+ const down = (e: KeyboardEvent) => {+ if (e.key === "k" && (e.metaKey || e.ctrlKey)) {+ e.preventDefault();+ setOpen((open) => !open);+ }+ };+ document.addEventListener("keydown", down);+ return () => document.removeEventListener("keydown", down);+ }, []);++ const handleKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === "Enter") {+ e.preventDefault();+ window.location.href = `/search${querySerializer(options)}`;+ }+ };++ return (+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogTitle className="sr-only">Search Command</DialogTitle>+ <CustomDialogContent+ className="p-2 max-w-screen-sm"+ customClose={+ options.query ? (+ <a href={`/search${querySerializer(options)}`}>+ <ArrowRight className="w-4 h-4" />+ </a>+ ) : (+ <XIcon className="w-4 h-4" />+ )+ }+ >+ <Input+ value={options?.query || ""}+ className="focus-visible:outline-none focus-visible:ring-0 focus-visible:ring-offset-0 ring-0 outline-none border-0"+ placeholder="Search..."+ onChange={(e) => {+ setOptions((prev) => ({ ...prev, query: e.target.value }));+ }}+ onKeyDown={handleKeyDown}+ />+ <div className="flex w-full gap-10">+ <div className="w-1/2">+ <AppSelect+ apps={options.apps || []}+ setApps={(values) => {+ setOptions((prev) => ({ ...prev, apps: values }));+ }}+ />+ </div>+ <div className="w-1/2">+ <DatePickerWithRange+ start_time={options.start_time}+ end_time={options.end_time}+ setDateRange={(range) => {+ setOptions((prev) => ({+ ...prev,+ start_time: range?.from ?? null,+ end_time: range?.to ?? null,+ }));+ }}+ />+ </div>+ </div>+ </CustomDialogContent>+ </Dialog>+ );+}++interface AppSelectProps {+ apps: string[];+ setApps: (values: string[]) => void;+}++export function AppSelect({ apps, setApps }: AppSelectProps) {+ const { items, isLoading } = useSqlAutocomplete("app");++ const appItems = React.useMemo(() => {+ return items.map((app) => ({+ value: app.name,+ count: app.count,+ label: app.name,+ }));+ }, [items]);++ const renderTech = (option: (typeof appItems)[number]) => (+ <div className="flex items-center gap-2">+ <span className="text-xl">+ <img+ src={`http://localhost:11435/app-icon?name=${option.value}`}+ className="w-6 h-6"+ alt={option.value}+ loading="lazy"+ decoding="async"+ />+ </span>+ <div className="flex flex-col">+ <span>{option.label}</span>+ </div>+ </div>+ );++ const renderSelected = (value: string[]) => (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger className="h-full">+ <div className="flex gap-1 h-full">+ {value.map((id) => {+ const tech = appItems.find((t) => t.value === id)!;++ if (!tech) return;+ return (+ <span key={id}>+ {+ <img+ src={`http://localhost:11435/app-icon?name=${tech.label}`}+ className="w-6 h-6"+ alt={tech.label}+ loading="lazy"+ decoding="async"+ />+ }+ </span>+ );+ })}+ </div>+ </TooltipTrigger>+ <TooltipContent>+ {value.map((id) => {+ const tech = appItems.find((t) => t.value === id)!;+ if (!tech) return;+ return <div key={id}>{tech.label}</div>;+ })}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ );++ return (+ <MultiSelectCombobox+ label="Applications"+ options={appItems}+ value={apps}+ onChange={setApps}+ renderItem={renderTech}+ renderSelectedItem={renderSelected}+ isLoading={isLoading}+ />+ );+}diff --git a/pipes/rewind/src/components/settings-provider.tsx b/pipes/rewind/src/components/settings-provider.tsxnew file mode 100644index 000000000..0456c477d--- /dev/null+++ b/pipes/rewind/src/components/settings-provider.tsx@@ -0,0 +1,67 @@+"use client";++import {+ getScreenpipeAppSettings,+ updateScreenpipeAppSettings,+} from "@/lib/actions/get-screenpipe-app-settings";+import { Settings } from "@screenpipe/js";+import { createContext, ReactNode, useEffect, useState } from "react";++export const SettingsContext = createContext<{+ settings: Partial<Settings> | null;+ loading: boolean;+ updateSettings: (value: Partial<Settings>) => Promise<boolean>;+} | null>(null);++export const SettingsProvider = ({ children }: { children: ReactNode }) => {+ const [settings, setSettings] = useState<Partial<Settings> | null>(null);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ loadSettings();+ console.log("fetched");+ }, []);++ const loadSettings = async () => {+ try {+ // Load screenpipe app settings+ const screenpipeSettings = await getScreenpipeAppSettings();++ // Merge everything together+ setSettings({+ ...screenpipeSettings,+ });+ } catch (error) {+ console.error("failed to load settings:", error);+ } finally {+ setLoading(false);+ }+ };++ const updateSettings = async (screenpipeAppSettings: Partial<Settings>) => {+ try {+ // Update screenpipe settings if provided+ if (screenpipeAppSettings) {+ await updateScreenpipeAppSettings({+ ...settings,+ ...screenpipeAppSettings,+ });+ }++ // Update state with everything+ setSettings({+ ...screenpipeAppSettings,+ });+ return true;+ } catch (error) {+ console.error("failed to update settings:", error);+ return false;+ }+ };++ return (+ <SettingsContext.Provider value={{ settings, loading, updateSettings }}>+ {children}+ </SettingsContext.Provider>+ );+};diff --git a/pipes/rewind/src/components/timeline/ai-panel.tsx b/pipes/rewind/src/components/timeline/ai-panel.tsxindex 1c1a53c98..699b4b38a 100644--- a/pipes/rewind/src/components/timeline/ai-panel.tsx+++ b/pipes/rewind/src/components/timeline/ai-panel.tsx@@ -231,10 +231,10 @@ export function AIPanel({const openai = new OpenAI({apiKey:- settings.aiProviderType === "screenpipe-cloud"- ? settings.user.token- : settings.openaiApiKey,- baseURL: settings.aiUrl,+ settings?.aiProviderType === "screenpipe-cloud"+ ? settings?.user?.token+ : settings?.openaiApiKey,+ baseURL: settings?.aiUrl,dangerouslyAllowBrowser: true,});@@ -248,7 +248,7 @@ export function AIPanel({relevantFrames,openai,{- model: settings.aiModel,+ model: settings?.aiModel || "",onProgress: (chunk) => {currentResponse = chunk;setChatMessages((prev) => [@@ -384,7 +384,7 @@ export function AIPanel({<Bot className="h-4 w-4 text-muted-foreground" /></TooltipTrigger><TooltipContent>- <p className="text-xs">using {settings.aiModel}</p>+ <p className="text-xs">using {settings?.aiModel}</p></TooltipContent></Tooltip></TooltipProvider>diff --git a/pipes/rewind/src/components/timeline/timeline-search.tsx b/pipes/rewind/src/components/timeline/timeline-search.tsxindex 9eb094e75..7e14df5c1 100644--- a/pipes/rewind/src/components/timeline/timeline-search.tsx+++ b/pipes/rewind/src/components/timeline/timeline-search.tsx@@ -5,329 +5,329 @@ import { Search, RefreshCw, Loader2, Square } from "lucide-react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import {- Dialog,- DialogContent,- DialogTitle,- DialogPortal,- DialogOverlay,+ Dialog,+ DialogContent,+ DialogTitle,+ DialogPortal,+ DialogOverlay,} from "@/components/ui/dialog";import { motion, AnimatePresence } from "framer-motion";import { StreamTimeSeriesResponse } from "@/app/page";import OpenAI from "openai";import { useSettings } from "@/lib/hooks/use-settings";import {- Tooltip,- TooltipContent,- TooltipProvider,- TooltipTrigger,+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,} from "@/components/ui/tooltip";interface TimelineSearchProps {- frames: StreamTimeSeriesResponse[];- onResultSelect: (index: number) => void;+ frames: StreamTimeSeriesResponse[];+ onResultSelect: (index: number) => void;}interface SearchParams {- keywords: string[];+ keywords: string[];}interface AppStats {- apps: Record<string, number>;- windows: Record<string, number>;- maxItems: number;+ apps: Record<string, number>;+ windows: Record<string, number>;+ maxItems: number;}function isValidSearchParams(obj: any): obj is SearchParams {- return (- obj &&- typeof obj === "object" &&- Array.isArray(obj.keywords) &&- obj.keywords.every((keyword: string) => typeof keyword === "string")- );+ return (+ obj &&+ typeof obj === "object" &&+ Array.isArray(obj.keywords) &&+ obj.keywords.every((keyword: string) => typeof keyword === "string")+ );}async function validateFrameContext(- frames: StreamTimeSeriesResponse[],- centerIndex: number,- searchParams: SearchParams,- openai: OpenAI,- model: string,- systemPrompt: string+ frames: StreamTimeSeriesResponse[],+ centerIndex: number,+ searchParams: SearchParams,+ openai: OpenAI,+ model: string,+ systemPrompt: string,): Promise<{ isRelevant: boolean; confidence: number; reason: string }> {- console.log("validating context for frame:", {- centerIndex,- searchParams,- model,- });-- const windowSize = 1000;- const start = Math.max(0, centerIndex - windowSize);- const end = Math.min(frames.length - 1, centerIndex + windowSize);-- const contextFrames = frames.slice(start, end + 1);- const contextData = contextFrames.map((frame) => ({- ocr: frame.devices.map((d) => d.metadata.ocr_text || "").join(" "),- transcripts: frame.devices- .flatMap((d) => d.audio.map((a) => a.transcription || ""))- .join(" "),- apps: frame.devices.map((d) => d.metadata.app_name || "").join(", "),- windows: frame.devices.map((d) => d.metadata.window_name || "").join(", "),- }));-- console.log("context data being sent to AI:", contextData);-- const response = await openai.chat.completions.create({- model,- messages: [- {- role: "system",- content: systemPrompt,- },- {- role: "user",- content: `given the search parameters: ${JSON.stringify(searchParams)}+ console.log("validating context for frame:", {+ centerIndex,+ searchParams,+ model,+ });++ const windowSize = 1000;+ const start = Math.max(0, centerIndex - windowSize);+ const end = Math.min(frames.length - 1, centerIndex + windowSize);++ const contextFrames = frames.slice(start, end + 1);+ const contextData = contextFrames.map((frame) => ({+ ocr: frame.devices.map((d) => d.metadata.ocr_text || "").join(" "),+ transcripts: frame.devices+ .flatMap((d) => d.audio.map((a) => a.transcription || ""))+ .join(" "),+ apps: frame.devices.map((d) => d.metadata.app_name || "").join(", "),+ windows: frame.devices.map((d) => d.metadata.window_name || "").join(", "),+ }));++ console.log("context data being sent to AI:", contextData);++ const response = await openai.chat.completions.create({+ model,+ messages: [+ {+ role: "system",+ content: systemPrompt,+ },+ {+ role: "user",+ content: `given the search parameters: ${JSON.stringify(searchParams)}and these surrounding frames: ${JSON.stringify(contextData)}-+determine if this is truly a relevant match.output format: {"isRelevant": boolean,"confidence": number, // 0-1"reason": string // brief explanation}`,- },- ],- response_format: { type: "json_object" },- });-- console.log(- "validation response from AI:",- response.choices[0]?.message?.content- );-- if (!response.choices?.[0]?.message?.content) {- throw new Error(- "invalid or empty response from ai:" + JSON.stringify(response, null, 2)- );- }-- return JSON.parse(response.choices[0].message.content);+ },+ ],+ response_format: { type: "json_object" },+ });++ console.log(+ "validation response from AI:",+ response.choices[0]?.message?.content,+ );++ if (!response.choices?.[0]?.message?.content) {+ throw new Error(+ "invalid or empty response from ai:" + JSON.stringify(response, null, 2),+ );+ }++ return JSON.parse(response.choices[0].message.content);}-async function findRelevantFrame(- query: string,- frames: StreamTimeSeriesResponse[],- openai: OpenAI,- model: string,- onProgress: (status: string) => void,- systemPrompt: string,- recursionDepth: number = 0,- previousValidation?: { reason: string },- signal?: AbortSignal+ query: string,+ frames: StreamTimeSeriesResponse[],+ openai: OpenAI,+ model: string,+ onProgress: (status: string) => void,+ systemPrompt: string,+ recursionDepth: number = 0,+ previousValidation?: { reason: string },+ signal?: AbortSignal,): Promise<number | null> {- if (signal?.aborted) {- throw new Error("AbortError");- }-- console.log("starting search with:", {- query,- model,- recursionDepth,- previousValidation,- });-- // prevent infinite recursion- if (recursionDepth >= 2) {- return null;- }-- onProgress("analyzing your search query to understand what to look for...");-- // enhance query with previous validation feedback- const enhancedQuery = previousValidation- ? `${query} (considering: ${previousValidation.reason})`- : query;-- try {- const response = await openai.chat.completions.create({- model: model,- messages: [- {- role: "system",- content: systemPrompt,- },- {- role: "user",- content: `analyze this search query and extract key information: "${enhancedQuery}"+ if (signal?.aborted) {+ throw new Error("AbortError");+ }++ console.log("starting search with:", {+ query,+ model,+ recursionDepth,+ previousValidation,+ });++ // prevent infinite recursion+ if (recursionDepth >= 2) {+ return null;+ }++ onProgress("analyzing your search query to understand what to look for...");++ // enhance query with previous validation feedback+ const enhancedQuery = previousValidation+ ? `${query} (considering: ${previousValidation.reason})`+ : query;++ try {+ const response = await openai.chat.completions.create({+ model: model,+ messages: [+ {+ role: "system",+ content: systemPrompt,+ },+ {+ role: "user",+ content: `analyze this search query and extract key information: "${enhancedQuery}"output format: {"keywords": string[] // important keywords to match, must be non-empty array}-+for example, if the user asks "when i was doing annual reflections in obsidian", the output should be:{"keywords": ["obsidian", "annual reflections"]}-+if the user asks "when i was watching a youtube video about rust", the output should be:{"keywords": ["youtube", "rust", "video"]}`,- },- ],- response_format: { type: "json_object" },- });-- console.log(- "search params response from AI:",- response.choices[0]?.message?.content- );-- if (!response.choices?.[0]?.message?.content) {- throw new Error(- "invalid or empty response from ai:" + JSON.stringify(response, null, 2)- );- }-- const jsonContent = response.choices[0].message.content;- const parsed = JSON.parse(jsonContent);- console.log("parsed search params:", parsed);-- if (!isValidSearchParams(parsed)) {- throw new Error(- "invalid or malformed search parameters from ai response"- );- }-- const searchParams = parsed;-- onProgress(- `searching for moments containing: ${searchParams.keywords.join(", ")}...`- );-- await new Promise((resolve) => setTimeout(resolve, 1000));-- // Add early return after checking N frames- const MAX_FRAMES_TO_CHECK = 1000; // Adjust this number- let framesChecked = 0;-- const BATCH_SIZE = 2000; // Adjust based on performance needs- for (let i = 0; i < frames.length; i += BATCH_SIZE) {- if (signal?.aborted) {- throw new Error("AbortError");- }-- if (framesChecked >= MAX_FRAMES_TO_CHECK) {- onProgress("reached search limit. try being more specific.");- return null;- }-- // Process frames in batches- const batchFrames = frames.slice(i, i + BATCH_SIZE);- const potentialMatches: number[] = [];-- // First pass: quick keyword matching on the batch- batchFrames.forEach((frame, batchIndex) => {- const globalIndex = i + batchIndex;-- const hasMatch = frame.devices.some((device) =>- searchParams.keywords.some((keyword) => {- const keywordLower = keyword.toLowerCase();- return (- device.metadata.app_name?.toLowerCase().includes(keywordLower) ||- device.metadata.window_name- ?.toLowerCase()- .includes(keywordLower) ||- device.metadata.ocr_text?.toLowerCase().includes(keywordLower) ||- device.audio.some((a) =>- a.transcription?.toLowerCase().includes(keywordLower)- )- );- })- );-- if (hasMatch) {- potentialMatches.push(globalIndex);- }- });-- // If we found matches in this batch, validate them- if (potentialMatches.length > 0) {- onProgress(- `found ${potentialMatches.length} potential matches, analyzing context...`- );-- // Validate the most promising matches first (you could add scoring here)- for (const matchIndex of potentialMatches) {- const validation = await validateFrameContext(- frames,- matchIndex,- searchParams,- openai,- model,- systemPrompt- );-- if (validation.isRelevant && validation.confidence > 0.7) {- onProgress(- `found a highly relevant match! jumping to that moment...`- );- return matchIndex;- }- }-- framesChecked += potentialMatches.length;- console.log("frames checked:", framesChecked);- }- }-- onProgress(- `couldn't find an exact match. try being more specific about the app or content you're looking for.`- );- return null;- } catch (error: any) {- if (error.includes("AbortError")) {- console.log("search aborted");- } else {- console.error("search parameter parsing error:", error);- onProgress(- `oops! something went wrong with the search. please try again.`- );- }- throw new Error(`failed to parse search parameters: ${error}`);- }+ },+ ],+ response_format: { type: "json_object" },+ });++ console.log(+ "search params response from AI:",+ response.choices[0]?.message?.content,+ );++ if (!response.choices?.[0]?.message?.content) {+ throw new Error(+ "invalid or empty response from ai:" ++ JSON.stringify(response, null, 2),+ );+ }++ const jsonContent = response.choices[0].message.content;+ const parsed = JSON.parse(jsonContent);+ console.log("parsed search params:", parsed);++ if (!isValidSearchParams(parsed)) {+ throw new Error(+ "invalid or malformed search parameters from ai response",+ );+ }++ const searchParams = parsed;++ onProgress(+ `searching for moments containing: ${searchParams.keywords.join(", ")}...`,+ );++ await new Promise((resolve) => setTimeout(resolve, 1000));++ // Add early return after checking N frames+ const MAX_FRAMES_TO_CHECK = 1000; // Adjust this number+ let framesChecked = 0;++ const BATCH_SIZE = 2000; // Adjust based on performance needs+ for (let i = 0; i < frames.length; i += BATCH_SIZE) {+ if (signal?.aborted) {+ throw new Error("AbortError");+ }++ if (framesChecked >= MAX_FRAMES_TO_CHECK) {+ onProgress("reached search limit. try being more specific.");+ return null;+ }++ // Process frames in batches+ const batchFrames = frames.slice(i, i + BATCH_SIZE);+ const potentialMatches: number[] = [];++ // First pass: quick keyword matching on the batch+ batchFrames.forEach((frame, batchIndex) => {+ const globalIndex = i + batchIndex;++ const hasMatch = frame.devices.some((device) =>+ searchParams.keywords.some((keyword) => {+ const keywordLower = keyword.toLowerCase();+ return (+ device.metadata.app_name?.toLowerCase().includes(keywordLower) ||+ device.metadata.window_name+ ?.toLowerCase()+ .includes(keywordLower) ||+ device.metadata.ocr_text?.toLowerCase().includes(keywordLower) ||+ device.audio.some((a) =>+ a.transcription?.toLowerCase().includes(keywordLower),+ )+ );+ }),+ );++ if (hasMatch) {+ potentialMatches.push(globalIndex);+ }+ });++ // If we found matches in this batch, validate them+ if (potentialMatches.length > 0) {+ onProgress(+ `found ${potentialMatches.length} potential matches, analyzing context...`,+ );++ // Validate the most promising matches first (you could add scoring here)+ for (const matchIndex of potentialMatches) {+ const validation = await validateFrameContext(+ frames,+ matchIndex,+ searchParams,+ openai,+ model,+ systemPrompt,+ );++ if (validation.isRelevant && validation.confidence > 0.7) {+ onProgress(+ `found a highly relevant match! jumping to that moment...`,+ );+ return matchIndex;+ }+ }++ framesChecked += potentialMatches.length;+ console.log("frames checked:", framesChecked);+ }+ }++ onProgress(+ `couldn't find an exact match. try being more specific about the app or content you're looking for.`,+ );+ return null;+ } catch (error: any) {+ if (error.includes("AbortError")) {+ console.log("search aborted");+ } else {+ console.error("search parameter parsing error:", error);+ onProgress(+ `oops! something went wrong with the search. please try again.`,+ );+ }+ throw new Error(`failed to parse search parameters: ${error}`);+ }}async function generateSuggestions(- openai: OpenAI,- model: string,- systemPrompt: string,- appStats: AppStats+ openai: OpenAI,+ model: string,+ systemPrompt: string,+ appStats: AppStats,): Promise<string[]> {- console.log("generating suggestions with stats:", {- model,- appStats,- });-- try {- const response = await openai.chat.completions.create({- model,- messages: [- {- role: "system",- content: systemPrompt,- },- {- role: "user",- content: `generate 5 natural search suggestions based on the most common apps and activities in the user's data.+ console.log("generating suggestions with stats:", {+ model,+ appStats,+ });++ try {+ const response = await openai.chat.completions.create({+ model,+ messages: [+ {+ role: "system",+ content: systemPrompt,+ },+ {+ role: "user",+ content: `generate 5 natural search suggestions based on the most common apps and activities in the user's data.use this app statistics:apps: ${JSON.stringify(appStats.apps)}windows: ${JSON.stringify(appStats.windows)}-+output format: {"suggestions": string[] // array of 5 natural language search queries}-+make them specific and varied, focusing on different types of activities.example output:{@@ -339,163 +339,162 @@ async function generateSuggestions("that time i was debugging in chrome devtools"]}`,- },- ],- response_format: { type: "json_object" },- });-- console.log("suggestions response from AI:", response);-- if (!response.choices?.[0]?.message?.content) {- throw new Error("invalid or empty response from ai");- }-- const parsed = JSON.parse(response.choices[0].message.content);- return parsed.suggestions || [];- } catch (error) {- console.warn("failed to generate suggestions:", error);- return [- "when i was coding in vscode",- "that meeting in google meet",- "when i opened figma",- "that youtube video about rust",- "when i was writing in notion",- ];- }+ },+ ],+ response_format: { type: "json_object" },+ });++ console.log("suggestions response from AI:", response);++ if (!response.choices?.[0]?.message?.content) {+ throw new Error("invalid or empty response from ai");+ }++ const parsed = JSON.parse(response.choices[0].message.content);+ return parsed.suggestions || [];+ } catch (error) {+ console.warn("failed to generate suggestions:", error);+ return [+ "when i was coding in vscode",+ "that meeting in google meet",+ "when i opened figma",+ "that youtube video about rust",+ "when i was writing in notion",+ ];+ }}const CACHE_KEY = "timeline_search_suggestions";const CACHE_DURATION_MS = 24 * 60 * 60 * 1000; // 24 hoursinterface CachedSuggestions {- suggestions: string[];- timestamp: number;- appsHash: string; // to invalidate if apps change significantly+ suggestions: string[];+ timestamp: number;+ appsHash: string; // to invalidate if apps change significantly}function generateAppsHash(appStats: AppStats): string {- // create a hash of top 5 apps to detect major changes- const topApps = Object.entries(appStats.apps)- .sort(([, a], [, b]) => b - a)- .slice(0, 5)- .map(([app]) => app)- .join("|");- return topApps;+ // create a hash of top 5 apps to detect major changes+ const topApps = Object.entries(appStats.apps)+ .sort(([, a], [, b]) => b - a)+ .slice(0, 5)+ .map(([app]) => app)+ .join("|");+ return topApps;}async function getCachedOrGenerateSuggestions(- openai: OpenAI,- model: string,- systemPrompt: string,- appStats: AppStats+ openai: OpenAI,+ model: string,+ systemPrompt: string,+ appStats: AppStats,): Promise<string[]> {- try {- const cached = localStorage.getItem(CACHE_KEY);- if (cached) {- const parsedCache: CachedSuggestions = JSON.parse(cached);- const isExpired = Date.now() - parsedCache.timestamp > CACHE_DURATION_MS;- const appsChanged = generateAppsHash(appStats) !== parsedCache.appsHash;-- if (!isExpired && !appsChanged) {- console.log("using cached suggestions");- return parsedCache.suggestions;- }- }-- const suggestions = await generateSuggestions(- openai,- model,- systemPrompt,- appStats- );-- // cache the new suggestions- const cacheData: CachedSuggestions = {- suggestions,- timestamp: Date.now(),- appsHash: generateAppsHash(appStats),- };- localStorage.setItem(CACHE_KEY, JSON.stringify(cacheData));-- return suggestions;- } catch (error) {- console.warn("failed to handle suggestions:", error);- return [- "when i was coding in vscode",- "that meeting in google meet",- "when i opened figma",- "that youtube video about rust",- "when i was writing in notion",- ];- }+ try {+ const cached = localStorage.getItem(CACHE_KEY);+ if (cached) {+ const parsedCache: CachedSuggestions = JSON.parse(cached);+ const isExpired = Date.now() - parsedCache.timestamp > CACHE_DURATION_MS;+ const appsChanged = generateAppsHash(appStats) !== parsedCache.appsHash;++ if (!isExpired && !appsChanged) {+ console.log("using cached suggestions");+ return parsedCache.suggestions;+ }+ }++ const suggestions = await generateSuggestions(+ openai,+ model,+ systemPrompt,+ appStats,+ );++ // cache the new suggestions+ const cacheData: CachedSuggestions = {+ suggestions,+ timestamp: Date.now(),+ appsHash: generateAppsHash(appStats),+ };+ localStorage.setItem(CACHE_KEY, JSON.stringify(cacheData));++ return suggestions;+ } catch (error) {+ console.warn("failed to handle suggestions:", error);+ return [+ "when i was coding in vscode",+ "that meeting in google meet",+ "when i opened figma",+ "that youtube video about rust",+ "when i was writing in notion",+ ];+ }}export function TimelineSearch({- frames,- onResultSelect,+ frames,+ onResultSelect,}: TimelineSearchProps) {- const [open, setOpen] = useState(false);- const [searchQuery, setSearchQuery] = useState("");- const [searchStatus, setSearchStatus] = useState("");- const [isSearching, setIsSearching] = useState(false);- const { settings } = useSettings();- const [suggestions, setSuggestions] = useState<string[] | null>(null);- const [isLoadingSuggestions, setIsLoadingSuggestions] = useState(false);- const hasLoadedSuggestions = useRef(false);- const [abortController, setAbortController] =- useState<AbortController | null>(null);--- // Compute app statistics once when component mounts or frames update- const appStats = useMemo(() => {- const stats: AppStats = {- apps: {},- windows: {},- maxItems: 10, // Keep top N most common- };-- frames.forEach((frame) => {- frame.devices.forEach((device) => {- if (device.metadata.app_name) {- stats.apps[device.metadata.app_name] =- (stats.apps[device.metadata.app_name] || 0) + 1;- }- if (device.metadata.window_name) {- stats.windows[device.metadata.window_name] =- (stats.windows[device.metadata.window_name] || 0) + 1;- }- });- });-- // Sort and keep only top N- const topApps = Object.entries(stats.apps)- .sort(([, a], [, b]) => b - a)- .slice(0, stats.maxItems)- .reduce((obj, [key, val]) => ({ ...obj, [key]: val }), {});-- const topWindows = Object.entries(stats.windows)- .sort(([, a], [, b]) => b - a)- .slice(0, stats.maxItems)- .reduce((obj, [key, val]) => ({ ...obj, [key]: val }), {});-- return {- ...stats,- apps: topApps,- windows: topWindows,- };- }, [frames]);-- // Generate system prompt with app statistics- const getSystemPrompt = useCallback(() => {- const appsList = Object.entries(appStats.apps)- .map(([app, count]) => `${app} (${count} occurrences)`)- .join(", ");-- const windowsList = Object.entries(appStats.windows)- .map(([window, count]) => `${window} (${count} occurrences)`)- .join(", ");-- return `you are a search assistant for screenpipe, a system that continuously records screens & mics.+ const [open, setOpen] = useState(false);+ const [searchQuery, setSearchQuery] = useState("");+ const [searchStatus, setSearchStatus] = useState("");+ const [isSearching, setIsSearching] = useState(false);+ const { settings } = useSettings();+ const [suggestions, setSuggestions] = useState<string[] | null>(null);+ const [isLoadingSuggestions, setIsLoadingSuggestions] = useState(false);+ const hasLoadedSuggestions = useRef(false);+ const [abortController, setAbortController] =+ useState<AbortController | null>(null);++ // Compute app statistics once when component mounts or frames update+ const appStats = useMemo(() => {+ const stats: AppStats = {+ apps: {},+ windows: {},+ maxItems: 10, // Keep top N most common+ };++ frames.forEach((frame) => {+ frame.devices.forEach((device) => {+ if (device.metadata.app_name) {+ stats.apps[device.metadata.app_name] =+ (stats.apps[device.metadata.app_name] || 0) + 1;+ }+ if (device.metadata.window_name) {+ stats.windows[device.metadata.window_name] =+ (stats.windows[device.metadata.window_name] || 0) + 1;+ }+ });+ });++ // Sort and keep only top N+ const topApps = Object.entries(stats.apps)+ .sort(([, a], [, b]) => b - a)+ .slice(0, stats.maxItems)+ .reduce((obj, [key, val]) => ({ ...obj, [key]: val }), {});++ const topWindows = Object.entries(stats.windows)+ .sort(([, a], [, b]) => b - a)+ .slice(0, stats.maxItems)+ .reduce((obj, [key, val]) => ({ ...obj, [key]: val }), {});++ return {+ ...stats,+ apps: topApps,+ windows: topWindows,+ };+ }, [frames]);++ // Generate system prompt with app statistics+ const getSystemPrompt = useCallback(() => {+ const appsList = Object.entries(appStats.apps)+ .map(([app, count]) => `${app} (${count} occurrences)`)+ .join(", ");++ const windowsList = Object.entries(appStats.windows)+ .map(([window, count]) => `${window} (${count} occurrences)`)+ .join(", ");++ return `you are a search assistant for screenpipe, a system that continuously records screens & mics.your task is to analyze search queries and extract key information to find specific moments in the timeline.be extremely strict about matches - all keywords must be present in the correct context.@@ -533,7 +532,7 @@ examples of strict matching:✓ good match: {app_name: "Cursor", window_name: "db.rs - screenpipe", ocr_text: "fn main() {..."}✗ bad match: {app_name: "Cursor", window_name: "meeting notes", ocr_text: "discussing db.rs"}-- query: "watching rust video on youtube"+- query: "watching rust video on youtube"✓ good match: {app_name: "Chrome", window_name: "Rust Tutorial - YouTube", transcription: "today we'll learn rust"}✗ bad match: {app_name: "Chrome", window_name: "YouTube", transcription: "discussing databases"}@@ -545,305 +544,309 @@ focus on extracting:output only valid json with the exact structure requested.prioritize precision over recall - better to return no match than a wrong match.`;- }, [appStats]);-- const loadSuggestionsIfNeeded = useCallback(() => {- if (- !hasLoadedSuggestions.current &&- frames.length > 1_000 &&- !suggestions- ) {- hasLoadedSuggestions.current = true;- setIsLoadingSuggestions(true);-- const openai = new OpenAI({- apiKey:- settings.aiProviderType === "screenpipe-cloud"- ? settings.user.token- : settings.openaiApiKey,- baseURL: settings.aiUrl,- dangerouslyAllowBrowser: true,- });-- getCachedOrGenerateSuggestions(- openai,- settings.aiModel,- getSystemPrompt(),- appStats- )- .then(setSuggestions)- .catch((error) => {- console.warn("failed to load suggestions:", error);- setSuggestions([- "last meeting in google meet",- "last time i was working on linkedin",- "last youtube video i watched",- "last time i was writing in notion",- ]);- })- .finally(() => setIsLoadingSuggestions(false));- }- }, [frames.length, appStats, settings, suggestions]);-- // Only call when dialog opens- const handleOpen = useCallback(() => {- setOpen(true);- loadSuggestionsIfNeeded();- }, [loadSuggestionsIfNeeded]);-- const cancelSearch = useCallback(() => {- if (abortController) {- abortController.abort();- setIsSearching(false);- setSearchStatus("search cancelled");- }- }, [abortController]);-- const handleSearch = async (query: string) => {- const controller = new AbortController();- setAbortController(controller);-- setIsSearching(true);- setSearchStatus("");-- const openai = new OpenAI({- apiKey:- settings.aiProviderType === "screenpipe-cloud"- ? settings.user.token- : settings.openaiApiKey,- baseURL: settings.aiUrl,- dangerouslyAllowBrowser: true,- });-- try {- const systemPrompt = getSystemPrompt();-- const frameIndex = await findRelevantFrame(- query,- frames,- openai,- settings.aiModel,- (status) => setSearchStatus(status),- systemPrompt,- 0,- undefined,- controller.signal- );-- if (frameIndex !== null) {- onResultSelect(frameIndex);- setOpen(false);- } else {- setSearchStatus(- "couldn't find that moment. try being more specific about the app or content you're looking for."- );- }- } catch (error: any) {- if (error.includes("AbortError")) {- console.log("search aborted");- } else {- console.warn("search error:", error);- setSearchStatus("search failed. please try again.");- }- } finally {- setIsSearching(false);- setAbortController(null);- }- };-- const regenerateSuggestions = useCallback(async () => {- setIsLoadingSuggestions(true);- const openai = new OpenAI({- apiKey:- settings.aiProviderType === "screenpipe-cloud"- ? settings.user.token- : settings.openaiApiKey,- baseURL: settings.aiUrl,- dangerouslyAllowBrowser: true,- });-- try {- // Clear cache first- localStorage.removeItem(CACHE_KEY);-- const newSuggestions = await generateSuggestions(- openai,- settings.aiModel,- getSystemPrompt(),- appStats- );- setSuggestions(newSuggestions);-- // Update cache- const cacheData: CachedSuggestions = {- suggestions: newSuggestions,- timestamp: Date.now(),- appsHash: generateAppsHash(appStats),- };- localStorage.setItem(CACHE_KEY, JSON.stringify(cacheData));- } catch (error) {- console.warn("failed to regenerate suggestions:", error);- } finally {- setIsLoadingSuggestions(false);- }- }, [settings, appStats, getSystemPrompt]);-- return (- <>- <Button- variant="ghost"- size="icon"- onClick={handleOpen}- className="rounded-full"- >- <Search className="h-4 w-4" />- </Button>-- <Dialog- open={open}- onOpenChange={(newOpen) => {- if (!isSearching) {- setOpen(newOpen);- }- }}- >- <DialogPortal>- <DialogOverlay- className="backdrop-blur-sm"- style={{- opacity: isSearching ? 0 : 0.8,- }}- />- <motion.div- animate={{- x: isSearching ? 200 : 0,- transition: { duration: 0.3, ease: "easeInOut" },- }}- >- <DialogContent className="sm:max-w-[500px]">- <DialogTitle>Search your timeline</DialogTitle>- <motion.div- initial={{ opacity: 0, y: -20 }}- animate={{ opacity: 1, y: 0 }}- exit={{ opacity: 0, y: -20 }}- className="p-6"- >- <div className="relative">- <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />- <Input- autoFocus- placeholder="search in your timeline..."- className="pl-9 h-12"- value={searchQuery}- onChange={(e) => setSearchQuery(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter" && !isSearching) {- handleSearch(searchQuery);- }- }}- disabled={isSearching}- />- {isSearching && (- <Button- variant="ghost"- size="icon"- onClick={cancelSearch}- className="absolute right-2 top-1/2 -translate-y-1/2"- >- <Square className="h-4 w-4" />- </Button>- )}- </div>-- {searchStatus && (- <motion.div- initial={{ opacity: 0, y: 5 }}- animate={{ opacity: 1, y: 0 }}- className="mt-3 flex items-center gap-2 text-sm"- >- {isSearching && (- <Loader2 className="h-3 w-3 animate-spin text-primary" />- )}- <span- className={- isSearching ? "text-primary" : "text-muted-foreground"- }- >- {searchStatus}- </span>- </motion.div>- )}-- <motion.div- initial={{ opacity: 0 }}- animate={{ opacity: 1 }}- transition={{ delay: 0.1 }}- className="mt-4"- >- {suggestions && (- <div className="flex items-center justify-between mb-3">- <p className="text-sm text-muted-foreground">- suggested searches- </p>- <Button- variant="ghost"- size="icon"- onClick={regenerateSuggestions}- disabled={isLoadingSuggestions}- className="h-6 w-6"- >- <RefreshCw className="h-4 w-4" />- </Button>- </div>- )}- <div className="space-y-2">- {isLoadingSuggestions ? (- // Skeleton loading state- <>- {[1, 2, 3, 4, 5].map((i) => (- <div- key={i}- className="h-10 bg-muted rounded-md animate-pulse"- />- ))}- </>- ) : suggestions ? (- suggestions.map((suggestion, i) => (- <motion.div- key={suggestion}- initial={{ opacity: 0, x: -20 }}- animate={{ opacity: 1, x: 0 }}- transition={{ delay: 0.1 + i * 0.05 }}- >- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <Button- variant="ghost"- className="w-full justify-start text-left h-auto py-2 px-3 overflow-hidden"- onClick={() => handleSearch(suggestion)}- disabled={isSearching}- >- <div className="max-w-[400px] overflow-hidden text-ellipsis whitespace-nowrap">- {suggestion}- </div>- </Button>- </TooltipTrigger>- <TooltipContent side="top" align="start">- {suggestion}- </TooltipContent>- </Tooltip>- </TooltipProvider>- </motion.div>- ))- ) : null}- </div>- </motion.div>- </motion.div>- </DialogContent>- </motion.div>- </DialogPortal>- </Dialog>- </>- );+ }, [appStats]);++ const loadSuggestionsIfNeeded = useCallback(() => {+ if (!settings?.aiModel) {+ setSuggestions([]);+ return;+ }+ if (+ !hasLoadedSuggestions.current &&+ frames.length > 1_000 &&+ !suggestions+ ) {+ hasLoadedSuggestions.current = true;+ setIsLoadingSuggestions(true);++ const openai = new OpenAI({+ apiKey:+ settings?.aiProviderType === "screenpipe-cloud"+ ? settings?.user?.token+ : settings?.openaiApiKey,+ baseURL: settings?.aiUrl,+ dangerouslyAllowBrowser: true,+ });++ getCachedOrGenerateSuggestions(+ openai,+ settings?.aiModel,+ getSystemPrompt(),+ appStats,+ )+ .then(setSuggestions)+ .catch((error) => {+ console.warn("failed to load suggestions:", error);+ setSuggestions([+ "last meeting in google meet",+ "last time i was working on linkedin",+ "last youtube video i watched",+ "last time i was writing in notion",+ ]);+ })+ .finally(() => setIsLoadingSuggestions(false));+ }+ }, [frames.length, appStats, settings, suggestions]);++ // Only call when dialog opens+ const handleOpen = useCallback(() => {+ setOpen(true);+ loadSuggestionsIfNeeded();+ }, [loadSuggestionsIfNeeded]);++ const cancelSearch = useCallback(() => {+ if (abortController) {+ abortController.abort();+ setIsSearching(false);+ setSearchStatus("search cancelled");+ }+ }, [abortController]);++ const handleSearch = async (query: string) => {+ const controller = new AbortController();+ setAbortController(controller);++ setIsSearching(true);+ setSearchStatus("");++ const openai = new OpenAI({+ apiKey:+ settings?.aiProviderType === "screenpipe-cloud"+ ? settings?.user?.token+ : settings?.openaiApiKey,+ baseURL: settings?.aiUrl,+ dangerouslyAllowBrowser: true,+ });++ try {+ const systemPrompt = getSystemPrompt();++ const frameIndex = await findRelevantFrame(+ query,+ frames,+ openai,+ settings?.aiModel || "mistral",+ (status) => setSearchStatus(status),+ systemPrompt,+ 0,+ undefined,+ controller.signal,+ );++ if (frameIndex !== null) {+ onResultSelect(frameIndex);+ setOpen(false);+ } else {+ setSearchStatus(+ "couldn't find that moment. try being more specific about the app or content you're looking for.",+ );+ }+ } catch (error: any) {+ if (error.includes("AbortError")) {+ console.log("search aborted");+ } else {+ console.warn("search error:", error);+ setSearchStatus("search failed. please try again.");+ }+ } finally {+ setIsSearching(false);+ setAbortController(null);+ }+ };++ const regenerateSuggestions = useCallback(async () => {+ setIsLoadingSuggestions(true);+ const openai = new OpenAI({+ apiKey:+ settings?.aiProviderType === "screenpipe-cloud"+ ? settings?.user?.token+ : settings?.openaiApiKey,+ baseURL: settings?.aiUrl,+ dangerouslyAllowBrowser: true,+ });++ try {+ // Clear cache first+ localStorage.removeItem(CACHE_KEY);++ const newSuggestions = await generateSuggestions(+ openai,+ settings?.aiModel || "mistral",+ getSystemPrompt(),+ appStats,+ );+ setSuggestions(newSuggestions);++ // Update cache+ const cacheData: CachedSuggestions = {+ suggestions: newSuggestions,+ timestamp: Date.now(),+ appsHash: generateAppsHash(appStats),+ };+ localStorage.setItem(CACHE_KEY, JSON.stringify(cacheData));+ } catch (error) {+ console.warn("failed to regenerate suggestions:", error);+ } finally {+ setIsLoadingSuggestions(false);+ }+ }, [settings, appStats, getSystemPrompt]);++ return (+ <>+ <Button+ variant="ghost"+ size="icon"+ onClick={handleOpen}+ className="rounded-full"+ >+ <Search className="h-4 w-4" />+ </Button>++ <Dialog+ open={open}+ onOpenChange={(newOpen) => {+ if (!isSearching) {+ setOpen(newOpen);+ }+ }}+ >+ <DialogPortal>+ <DialogOverlay+ className="backdrop-blur-sm"+ style={{+ opacity: isSearching ? 0 : 0.8,+ }}+ />+ <motion.div+ animate={{+ x: isSearching ? 200 : 0,+ transition: { duration: 0.3, ease: "easeInOut" },+ }}+ >+ <DialogContent className="sm:max-w-[500px]">+ <DialogTitle>Search your timeline</DialogTitle>+ <motion.div+ initial={{ opacity: 0, y: -20 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: -20 }}+ className="p-6"+ >+ <div className="relative">+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />+ <Input+ autoFocus+ placeholder="search in your timeline..."+ className="pl-9 h-12"+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !isSearching) {+ handleSearch(searchQuery);+ }+ }}+ disabled={isSearching}+ />+ {isSearching && (+ <Button+ variant="ghost"+ size="icon"+ onClick={cancelSearch}+ className="absolute right-2 top-1/2 -translate-y-1/2"+ >+ <Square className="h-4 w-4" />+ </Button>+ )}+ </div>++ {searchStatus && (+ <motion.div+ initial={{ opacity: 0, y: 5 }}+ animate={{ opacity: 1, y: 0 }}+ className="mt-3 flex items-center gap-2 text-sm"+ >+ {isSearching && (+ <Loader2 className="h-3 w-3 animate-spin text-primary" />+ )}+ <span+ className={+ isSearching ? "text-primary" : "text-muted-foreground"+ }+ >+ {searchStatus}+ </span>+ </motion.div>+ )}++ <motion.div+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ transition={{ delay: 0.1 }}+ className="mt-4"+ >+ {suggestions && (+ <div className="flex items-center justify-between mb-3">+ <p className="text-sm text-muted-foreground">+ suggested searches+ </p>+ <Button+ variant="ghost"+ size="icon"+ onClick={regenerateSuggestions}+ disabled={isLoadingSuggestions}+ className="h-6 w-6"+ >+ <RefreshCw className="h-4 w-4" />+ </Button>+ </div>+ )}+ <div className="space-y-2">+ {isLoadingSuggestions ? (+ // Skeleton loading state+ <>+ {[1, 2, 3, 4, 5].map((i) => (+ <div+ key={i}+ className="h-10 bg-muted rounded-md animate-pulse"+ />+ ))}+ </>+ ) : suggestions ? (+ suggestions.map((suggestion, i) => (+ <motion.div+ key={suggestion}+ initial={{ opacity: 0, x: -20 }}+ animate={{ opacity: 1, x: 0 }}+ transition={{ delay: 0.1 + i * 0.05 }}+ >+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ className="w-full justify-start text-left h-auto py-2 px-3 overflow-hidden"+ onClick={() => handleSearch(suggestion)}+ disabled={isSearching}+ >+ <div className="max-w-[400px] overflow-hidden text-ellipsis whitespace-nowrap">+ {suggestion}+ </div>+ </Button>+ </TooltipTrigger>+ <TooltipContent side="top" align="start">+ {suggestion}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </motion.div>+ ))+ ) : null}+ </div>+ </motion.div>+ </motion.div>+ </DialogContent>+ </motion.div>+ </DialogPortal>+ </Dialog>+ </>+ );}diff --git a/pipes/rewind/src/components/ui/calendar.tsx b/pipes/rewind/src/components/ui/calendar.tsxindex 61d2b451e..4b1122924 100644--- a/pipes/rewind/src/components/ui/calendar.tsx+++ b/pipes/rewind/src/components/ui/calendar.tsx@@ -1,66 +1,66 @@-"use client"+"use client";-import * as React from "react"-import { ChevronLeft, ChevronRight } from "lucide-react"-import { DayPicker } from "react-day-picker"+import * as React from "react";+import { ChevronLeft, ChevronRight } from "lucide-react";+import { DayPicker } from "react-day-picker";-import { cn } from "@/lib/utils"-import { buttonVariants } from "@/components/ui/button"+import { cn } from "@/lib/utils";+import { buttonVariants } from "@/components/ui/button";-export type CalendarProps = React.ComponentProps<typeof DayPicker>+export type CalendarProps = React.ComponentProps<typeof DayPicker>;function Calendar({- className,- classNames,- showOutsideDays = true,- ...props+ className,+ classNames,+ showOutsideDays = true,+ ...props}: CalendarProps) {- return (- <DayPicker- showOutsideDays={showOutsideDays}- className={cn("p-3", className)}- classNames={{- months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",- month: "space-y-4",- caption: "flex justify-center pt-1 relative items-center",- caption_label: "text-sm font-medium",- nav: "space-x-1 flex items-center",- nav_button: cn(- buttonVariants({ variant: "outline" }),- "h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"- ),- nav_button_previous: "absolute left-1",- nav_button_next: "absolute right-1",- table: "w-full border-collapse space-y-1",- head_row: "flex",- head_cell:- "text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",- row: "flex w-full mt-2",- cell: "h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",- day: cn(- buttonVariants({ variant: "ghost" }),- "h-9 w-9 p-0 font-normal aria-selected:opacity-100"- ),- day_range_end: "day-range-end",- day_selected:- "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",- day_today: "bg-accent text-accent-foreground",- day_outside:- "day-outside text-muted-foreground aria-selected:bg-accent/50 aria-selected:text-muted-foreground",- day_disabled: "text-muted-foreground opacity-50",- day_range_middle:- "aria-selected:bg-accent aria-selected:text-accent-foreground",- day_hidden: "invisible",- ...classNames,- }}- components={{- IconLeft: ({ ...props }) => <ChevronLeft className="h-4 w-4" />,- IconRight: ({ ...props }) => <ChevronRight className="h-4 w-4" />,- }}- {...props}- />- )+ return (+ <DayPicker+ showOutsideDays={showOutsideDays}+ className={cn("p-3", className)}+ classNames={{+ months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",+ month: "space-y-4",+ caption: "flex justify-center pt-1 relative items-center",+ caption_label: "text-sm font-medium",+ nav: "space-x-1 flex items-center",+ nav_button: cn(+ buttonVariants({ variant: "outline" }),+ "h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100",+ ),+ nav_button_previous: "absolute left-1",+ nav_button_next: "absolute right-1",+ table: "w-full border-collapse space-y-1",+ head_row: "flex",+ head_cell:+ "text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",+ row: "flex w-full mt-2",+ cell: "h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",+ day: cn(+ buttonVariants({ variant: "ghost" }),+ "h-9 w-9 p-0 font-normal aria-selected:opacity-100",+ ),+ day_range_end: "day-range-end",+ day_selected:+ "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",+ day_today: "bg-accent text-accent-foreground",+ day_outside:+ "day-outside text-muted-foreground aria-selected:bg-accent/50 aria-selected:text-muted-foreground",+ day_disabled: "text-muted-foreground opacity-50",+ day_range_middle:+ "aria-selected:bg-accent aria-selected:text-accent-foreground",+ day_hidden: "invisible",+ ...classNames,+ }}+ components={{+ IconLeft: ({ ...props }) => <ChevronLeft className="h-4 w-4" />,+ IconRight: ({ ...props }) => <ChevronRight className="h-4 w-4" />,+ }}+ {...props}+ />+ );}-Calendar.displayName = "Calendar"+Calendar.displayName = "Calendar";-export { Calendar }+export { Calendar };diff --git a/pipes/rewind/src/components/ui/command.tsx b/pipes/rewind/src/components/ui/command.tsxindex 59a264529..103570b7b 100644--- a/pipes/rewind/src/components/ui/command.tsx+++ b/pipes/rewind/src/components/ui/command.tsx@@ -1,153 +1,156 @@-"use client"+"use client";-import * as React from "react"-import { type DialogProps } from "@radix-ui/react-dialog"-import { Command as CommandPrimitive } from "cmdk"-import { Search } from "lucide-react"+import * as React from "react";+import { type DialogProps } from "@radix-ui/react-dialog";+import { Command as CommandPrimitive } from "cmdk";+import { Search } from "lucide-react";-import { cn } from "@/lib/utils"-import { Dialog, DialogContent } from "@/components/ui/dialog"+import { cn } from "@/lib/utils";+import { Dialog, DialogContent } from "@/components/ui/dialog";const Command = React.forwardRef<- React.ElementRef<typeof CommandPrimitive>,- React.ComponentPropsWithoutRef<typeof CommandPrimitive>+ React.ElementRef<typeof CommandPrimitive>,+ React.ComponentPropsWithoutRef<typeof CommandPrimitive>>(({ className, ...props }, ref) => (- <CommandPrimitive- ref={ref}- className={cn(- "flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",- className- )}- {...props}- />-))-Command.displayName = CommandPrimitive.displayName+ <CommandPrimitive+ ref={ref}+ className={cn(+ "flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",+ className,+ )}+ {...props}+ />+));+Command.displayName = CommandPrimitive.displayName;const CommandDialog = ({ children, ...props }: DialogProps) => {- return (- <Dialog {...props}>- <DialogContent className="overflow-hidden p-0 shadow-lg">- <Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">- {children}- </Command>- </DialogContent>- </Dialog>- )-}+ return (+ <Dialog {...props}>+ <DialogContent className="overflow-hidden p-0 shadow-lg">+ <Command+ shouldFilter={false}+ className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5"+ >+ {children}+ </Command>+ </DialogContent>+ </Dialog>+ );+};const CommandInput = React.forwardRef<- React.ElementRef<typeof CommandPrimitive.Input>,- React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>+ React.ElementRef<typeof CommandPrimitive.Input>,+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>>(({ className, ...props }, ref) => (- <div className="flex items-center border-b px-3" cmdk-input-wrapper="">- <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />- <CommandPrimitive.Input- ref={ref}- className={cn(- "flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",- className- )}- {...props}- />- </div>-))--CommandInput.displayName = CommandPrimitive.Input.displayName+ <div className="flex items-center border-b px-3" cmdk-input-wrapper="">+ <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />+ <CommandPrimitive.Input+ ref={ref}+ className={cn(+ "flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",+ className,+ )}+ {...props}+ />+ </div>+));++CommandInput.displayName = CommandPrimitive.Input.displayName;const CommandList = React.forwardRef<- React.ElementRef<typeof CommandPrimitive.List>,- React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>+ React.ElementRef<typeof CommandPrimitive.List>,+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>>(({ className, ...props }, ref) => (- <CommandPrimitive.List- ref={ref}- className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)}- {...props}- />-))+ <CommandPrimitive.List+ ref={ref}+ className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)}+ {...props}+ />+));-CommandList.displayName = CommandPrimitive.List.displayName+CommandList.displayName = CommandPrimitive.List.displayName;const CommandEmpty = React.forwardRef<- React.ElementRef<typeof CommandPrimitive.Empty>,- React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>+ React.ElementRef<typeof CommandPrimitive.Empty>,+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>>((props, ref) => (- <CommandPrimitive.Empty- ref={ref}- className="py-6 text-center text-sm"- {...props}- />-))+ <CommandPrimitive.Empty+ ref={ref}+ className="py-6 text-center text-sm"+ {...props}+ />+));-CommandEmpty.displayName = CommandPrimitive.Empty.displayName+CommandEmpty.displayName = CommandPrimitive.Empty.displayName;const CommandGroup = React.forwardRef<- React.ElementRef<typeof CommandPrimitive.Group>,- React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>+ React.ElementRef<typeof CommandPrimitive.Group>,+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>>(({ className, ...props }, ref) => (- <CommandPrimitive.Group- ref={ref}- className={cn(- "overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",- className- )}- {...props}- />-))--CommandGroup.displayName = CommandPrimitive.Group.displayName+ <CommandPrimitive.Group+ ref={ref}+ className={cn(+ "overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",+ className,+ )}+ {...props}+ />+));++CommandGroup.displayName = CommandPrimitive.Group.displayName;const CommandSeparator = React.forwardRef<- React.ElementRef<typeof CommandPrimitive.Separator>,- React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>+ React.ElementRef<typeof CommandPrimitive.Separator>,+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>>(({ className, ...props }, ref) => (- <CommandPrimitive.Separator- ref={ref}- className={cn("-mx-1 h-px bg-border", className)}- {...props}- />-))-CommandSeparator.displayName = CommandPrimitive.Separator.displayName+ <CommandPrimitive.Separator+ ref={ref}+ className={cn("-mx-1 h-px bg-border", className)}+ {...props}+ />+));+CommandSeparator.displayName = CommandPrimitive.Separator.displayName;const CommandItem = React.forwardRef<- React.ElementRef<typeof CommandPrimitive.Item>,- React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>+ React.ElementRef<typeof CommandPrimitive.Item>,+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>>(({ className, ...props }, ref) => (- <CommandPrimitive.Item- ref={ref}- className={cn(- "relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",- className- )}- {...props}- />-))--CommandItem.displayName = CommandPrimitive.Item.displayName+ <CommandPrimitive.Item+ ref={ref}+ className={cn(+ "relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",+ className,+ )}+ {...props}+ />+));++CommandItem.displayName = CommandPrimitive.Item.displayName;const CommandShortcut = ({- className,- ...props+ className,+ ...props}: React.HTMLAttributes<HTMLSpanElement>) => {- return (- <span- className={cn(- "ml-auto text-xs tracking-widest text-muted-foreground",- className- )}- {...props}- />- )-}-CommandShortcut.displayName = "CommandShortcut"+ return (+ <span+ className={cn(+ "ml-auto text-xs tracking-widest text-muted-foreground",+ className,+ )}+ {...props}+ />+ );+};+CommandShortcut.displayName = "CommandShortcut";export {- Command,- CommandDialog,- CommandInput,- CommandList,- CommandEmpty,- CommandGroup,- CommandItem,- CommandShortcut,- CommandSeparator,-}+ Command,+ CommandDialog,+ CommandInput,+ CommandList,+ CommandEmpty,+ CommandGroup,+ CommandItem,+ CommandShortcut,+ CommandSeparator,+};diff --git a/pipes/rewind/src/components/ui/dialog.tsx b/pipes/rewind/src/components/ui/dialog.tsxindex 01ff19c7e..c97998772 100644--- a/pipes/rewind/src/components/ui/dialog.tsx+++ b/pipes/rewind/src/components/ui/dialog.tsx@@ -1,122 +1,122 @@-"use client"+"use client";-import * as React from "react"-import * as DialogPrimitive from "@radix-ui/react-dialog"-import { X } from "lucide-react"+import * as React from "react";+import * as DialogPrimitive from "@radix-ui/react-dialog";+import { X } from "lucide-react";-import { cn } from "@/lib/utils"+import { cn } from "@/lib/utils";-const Dialog = DialogPrimitive.Root+const Dialog = DialogPrimitive.Root;-const DialogTrigger = DialogPrimitive.Trigger+const DialogTrigger = DialogPrimitive.Trigger;-const DialogPortal = DialogPrimitive.Portal+const DialogPortal = DialogPrimitive.Portal;-const DialogClose = DialogPrimitive.Close+const DialogClose = DialogPrimitive.Close;const DialogOverlay = React.forwardRef<- React.ElementRef<typeof DialogPrimitive.Overlay>,- React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>+ React.ElementRef<typeof DialogPrimitive.Overlay>,+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>>(({ className, ...props }, ref) => (- <DialogPrimitive.Overlay- ref={ref}- className={cn(- "fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",- className- )}- {...props}- />-))-DialogOverlay.displayName = DialogPrimitive.Overlay.displayName+ <DialogPrimitive.Overlay+ ref={ref}+ className={cn(+ "fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",+ className,+ )}+ {...props}+ />+));+DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;const DialogContent = React.forwardRef<- React.ElementRef<typeof DialogPrimitive.Content>,- React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>+ React.ElementRef<typeof DialogPrimitive.Content>,+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>>(({ className, children, ...props }, ref) => (- <DialogPortal>- <DialogOverlay />- <DialogPrimitive.Content- ref={ref}- className={cn(- "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",- className- )}- {...props}- >- {children}- <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">- <X className="h-4 w-4" />- <span className="sr-only">Close</span>- </DialogPrimitive.Close>- </DialogPrimitive.Content>- </DialogPortal>-))-DialogContent.displayName = DialogPrimitive.Content.displayName+ <DialogPortal>+ <DialogOverlay />+ <DialogPrimitive.Content+ ref={ref}+ className={cn(+ "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",+ className,+ )}+ {...props}+ >+ {children}+ <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">+ <X className="h-4 w-4" />+ <span className="sr-only">Close</span>+ </DialogPrimitive.Close>+ </DialogPrimitive.Content>+ </DialogPortal>+));+DialogContent.displayName = DialogPrimitive.Content.displayName;const DialogHeader = ({- className,- ...props+ className,+ ...props}: React.HTMLAttributes<HTMLDivElement>) => (- <div- className={cn(- "flex flex-col space-y-1.5 text-center sm:text-left",- className- )}- {...props}- />-)-DialogHeader.displayName = "DialogHeader"+ <div+ className={cn(+ "flex flex-col space-y-1.5 text-center sm:text-left",+ className,+ )}+ {...props}+ />+);+DialogHeader.displayName = "DialogHeader";const DialogFooter = ({- className,- ...props+ className,+ ...props}: React.HTMLAttributes<HTMLDivElement>) => (- <div- className={cn(- "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",- className- )}- {...props}- />-)-DialogFooter.displayName = "DialogFooter"+ <div+ className={cn(+ "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",+ className,+ )}+ {...props}+ />+);+DialogFooter.displayName = "DialogFooter";const DialogTitle = React.forwardRef<- React.ElementRef<typeof DialogPrimitive.Title>,- React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>+ React.ElementRef<typeof DialogPrimitive.Title>,+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>>(({ className, ...props }, ref) => (- <DialogPrimitive.Title- ref={ref}- className={cn(- "text-lg font-semibold leading-none tracking-tight",- className- )}- {...props}- />-))-DialogTitle.displayName = DialogPrimitive.Title.displayName+ <DialogPrimitive.Title+ ref={ref}+ className={cn(+ "text-lg font-semibold leading-none tracking-tight",+ className,+ )}+ {...props}+ />+));+DialogTitle.displayName = DialogPrimitive.Title.displayName;const DialogDescription = React.forwardRef<- React.ElementRef<typeof DialogPrimitive.Description>,- React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>+ React.ElementRef<typeof DialogPrimitive.Description>,+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>>(({ className, ...props }, ref) => (- <DialogPrimitive.Description- ref={ref}- className={cn("text-sm text-muted-foreground", className)}- {...props}- />-))-DialogDescription.displayName = DialogPrimitive.Description.displayName+ <DialogPrimitive.Description+ ref={ref}+ className={cn("text-sm text-muted-foreground", className)}+ {...props}+ />+));+DialogDescription.displayName = DialogPrimitive.Description.displayName;export {- Dialog,- DialogPortal,- DialogOverlay,- DialogClose,- DialogTrigger,- DialogContent,- DialogHeader,- DialogFooter,- DialogTitle,- DialogDescription,-}+ Dialog,+ DialogPortal,+ DialogOverlay,+ DialogClose,+ DialogTrigger,+ DialogContent,+ DialogHeader,+ DialogFooter,+ DialogTitle,+ DialogDescription,+};diff --git a/pipes/rewind/src/components/ui/multi-select-combobox.tsx b/pipes/rewind/src/components/ui/multi-select-combobox.tsxnew file mode 100644index 000000000..903683f3d--- /dev/null+++ b/pipes/rewind/src/components/ui/multi-select-combobox.tsx@@ -0,0 +1,212 @@+import React, { useState } from "react";++// Third-party component imports+import { Check, ChevronsUpDown, LoaderCircle, X } from "lucide-react";++// Local UI component imports+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+} from "@/components/ui/command";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";++// Utility imports+import { cn } from "@/lib/utils";++/**+ * Base interface for option items in the multi-select combobox+ * @property label - Display text for the option+ * @property value - Unique identifier for the option+ */+export interface BaseOption {+ label: string;+ value: string;+}++/**+ * Generic type for extending BaseOption with additional properties+ */+export type Option<T extends BaseOption = BaseOption> = T;++/**+ * Props interface for the MultiSelectCombobox component+ * @template T - Type extending BaseOption+ */+interface Props<T extends BaseOption> {+ /** Label for the combobox */+ label: string;+ /** Custom render function for individual options */+ renderItem: (option: T) => React.ReactNode;+ /** Custom render function for selected items display */+ renderSelectedItem: (value: string[]) => React.ReactNode;+ /** Array of available options */+ options: T[];+ /** Array of selected values */+ value: string[];+ /** Callback function when selection changes */+ onChange: (value: string[]) => void;+ /** Optional placeholder text for search input */+ placeholder?: string;++ isLoading?: Boolean;+}++/**+ * A customizable multi-select combobox component with type safety+ * @template T - Type extending BaseOption+ */+export const MultiSelectCombobox = <T extends BaseOption>({+ label,+ renderItem,+ renderSelectedItem,+ options,+ value,+ onChange,+ placeholder,+ isLoading,+}: Props<T>) => {+ // State for controlling popover visibility+ const [open, setOpen] = useState(false);++ /**+ * Handles the selection/deselection of an option+ * @param currentValue - The value to toggle+ */+ const handleChange = (currentValue: string) => {+ onChange(+ value.includes(currentValue)+ ? value.filter((val) => val !== currentValue)+ : [...value, currentValue],+ );+ };++ /**+ * Clears all selected values+ */+ const handleClear = (e: React.MouseEvent) => {+ e.stopPropagation();+ onChange([]);+ };++ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <div+ role="combobox"+ aria-expanded={open}+ aria-haspopup="listbox"+ aria-controls="multi-select-options"+ aria-label={`Select ${label}`}+ tabIndex={0}+ className="flex h-10 min-w-[200px] cursor-pointer items-center justify-start gap-2 rounded-md border border-input bg-background px-4 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground focus:outline-none focus:ring-2 focus:ring-gray-300 focus:ring-offset-2"+ onClick={() => setOpen(!open)}+ onKeyDown={(e) => {+ if (e.key === "Enter" || e.key === " ") {+ setOpen(!open);+ }+ }}+ >+ {/* Icon and label section */}+ {+ //<ListFilter+ // className="size-4 shrink-0 text-muted-foreground"+ // aria-hidden="true"+ ///>+ }++ {isLoading && (+ <LoaderCircle+ className={cn("size-4 shrink-0 text-muted-foreground hidden", {+ "block animate-spin": isLoading,+ })}+ aria-hidden="true"+ />+ )}++ {+ // value.length > 0 && (+ // <span className="text-muted-foreground">{label}</span>+ //)+ }++ {/* Selected items display */}+ <div className="flex-1 overflow-hidden h-full text-muted-foreground">+ {value.length > 0+ ? renderSelectedItem(value)+ : `Filter by ${label}...`}+ </div>++ {/* Control buttons */}+ <span className="z-10 ml-auto flex items-center gap-2">+ {value.length > 0 && (+ <button+ type="button"+ aria-label="Clear selection"+ className="z-10 rounded-sm opacity-50 hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-gray-300"+ onClick={handleClear}+ >+ <X className="size-4 shrink-0" />+ </button>+ )}+ <ChevronsUpDown+ className="size-4 shrink-0 opacity-50"+ aria-hidden="true"+ />+ </span>+ </div>+ </PopoverTrigger>++ {/* Dropdown content */}+ <PopoverContent+ className="w-[--radix-popover-trigger-width] p-0"+ id="multi-select-options"+ >+ <Command>+ <CommandInput+ placeholder={placeholder || `Search ${label}...`}+ aria-label={`Search ${label}`}+ />+ <CommandList>+ <CommandEmpty>No {label} found.</CommandEmpty>+ <CommandGroup>+ {options.map((option) => (+ <CommandItem+ key={option.value}+ value={option.label}+ onSelect={() => handleChange(option.value)}+ aria-selected={value.includes(option.value)}+ className={cn({+ "bg-accent text-accent-foreground": value.includes(+ option.value,+ ),+ })}+ >+ {+ //<Check+ // className={cn(+ // "mr-2 h-4 w-4",+ // value.includes(option.value)+ // ? "opacity-100"+ // : "opacity-0",+ // )}+ // aria-hidden="true"+ ///>+ }+ {renderItem(option)}+ </CommandItem>+ ))}+ </CommandGroup>+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>+ );+};diff --git a/pipes/rewind/src/components/ui/popover.tsx b/pipes/rewind/src/components/ui/popover.tsxindex a0ec48bee..2213ab65b 100644--- a/pipes/rewind/src/components/ui/popover.tsx+++ b/pipes/rewind/src/components/ui/popover.tsx@@ -1,31 +1,48 @@-"use client"+"use client";-import * as React from "react"-import * as PopoverPrimitive from "@radix-ui/react-popover"+import * as React from "react";+import * as PopoverPrimitive from "@radix-ui/react-popover";-import { cn } from "@/lib/utils"+import { cn } from "@/lib/utils";-const Popover = PopoverPrimitive.Root+const Popover = PopoverPrimitive.Root;-const PopoverTrigger = PopoverPrimitive.Trigger+const PopoverTrigger = PopoverPrimitive.Trigger;const PopoverContent = React.forwardRef<- React.ElementRef<typeof PopoverPrimitive.Content>,- React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>+ React.ElementRef<typeof PopoverPrimitive.Content>,+ React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (- <PopoverPrimitive.Portal>- <PopoverPrimitive.Content- ref={ref}- align={align}- sideOffset={sideOffset}- className={cn(- "z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",- className- )}- {...props}- />- </PopoverPrimitive.Portal>-))-PopoverContent.displayName = PopoverPrimitive.Content.displayName+ <PopoverPrimitive.Portal>+ <PopoverPrimitive.Content+ ref={ref}+ align={align}+ sideOffset={sideOffset}+ className={cn(+ "z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",+ className,+ )}+ {...props}+ />+ </PopoverPrimitive.Portal>+));+PopoverContent.displayName = PopoverPrimitive.Content.displayName;-export { Popover, PopoverTrigger, PopoverContent }+const PopoverContentInDialog = React.forwardRef<+ React.ElementRef<typeof PopoverPrimitive.Content>,+ React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>+>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (+ <PopoverPrimitive.Content+ ref={ref}+ align={align}+ sideOffset={sideOffset}+ className={cn(+ "z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",+ className,+ )}+ {...props}+ />+));+PopoverContentInDialog.displayName = "PopoverContentInDialog";++export { Popover, PopoverTrigger, PopoverContent, PopoverContentInDialog };diff --git a/pipes/rewind/src/lib/actions/get-screenpipe-app-settings.ts b/pipes/rewind/src/lib/actions/get-screenpipe-app-settings.tsnew file mode 100644index 000000000..743c88999--- /dev/null+++ b/pipes/rewind/src/lib/actions/get-screenpipe-app-settings.ts@@ -0,0 +1,14 @@+"use server";++import { pipe } from "@screenpipe/js";+import type { Settings as ScreenpipeAppSettings } from "@screenpipe/js";++export async function getScreenpipeAppSettings() {+ return await pipe.settings.getAll();+}++export async function updateScreenpipeAppSettings(+ newSettings: Partial<ScreenpipeAppSettings>,+) {+ return await pipe.settings.update(newSettings);+}diff --git a/pipes/rewind/src/lib/hooks/use-ai-provider.tsx b/pipes/rewind/src/lib/hooks/use-ai-provider.tsxindex d784a47be..68b489dd7 100644--- a/pipes/rewind/src/lib/hooks/use-ai-provider.tsx+++ b/pipes/rewind/src/lib/hooks/use-ai-provider.tsx@@ -1,85 +1,95 @@import { useState, useEffect } from "react";-import type { Settings } from "@screenpipe/browser";+import type { Settings } from "@screenpipe/js";interface AIProviderStatus {- isAvailable: boolean;- error: string;+ isAvailable: boolean;+ error: string;}-export function useAiProvider(settings: Settings): AIProviderStatus {- const [status, setStatus] = useState<AIProviderStatus>({- isAvailable: true,- error: "",- });+export function useAiProvider(+ settings: Partial<Settings> | null | undefined,+): AIProviderStatus {+ const [status, setStatus] = useState<AIProviderStatus>({+ isAvailable: true,+ error: "",+ });- useEffect(() => {- const checkAiProvider = async () => {- try {- if (!settings.aiProviderType) {- setStatus({ isAvailable: false, error: "no ai-provider is set" });- return;- }- switch (settings.aiProviderType) {- case "openai":- if (!settings.openaiApiKey) {- setStatus({- isAvailable: false,- error: "openai api key not configured",- });- return;- }- break;+ useEffect(() => {+ const checkAiProvider = async () => {+ try {+ if (!settings) {+ setStatus({+ isAvailable: false,+ error: "no settings found",+ });+ return;+ }- case "native-ollama":- try {- const response = await fetch("http://localhost:11434/api/tags");- if (!response.ok) throw new Error();- } catch {- setStatus({- isAvailable: false,- error: "ollama not running on port 11434",- });- return;- }- break;+ if (!settings.aiProviderType) {+ setStatus({ isAvailable: false, error: "no ai-provider is set" });+ return;+ }+ switch (settings.aiProviderType) {+ case "openai":+ if (!settings.openaiApiKey) {+ setStatus({+ isAvailable: false,+ error: "openai api key not configured",+ });+ return;+ }+ break;- case "screenpipe-cloud":- if (!settings.user?.token) {- setStatus({- isAvailable: false,- error: "login required for screenpipe cloud",- });- return;- }- break;+ case "native-ollama":+ try {+ const response = await fetch("http://localhost:11434/api/tags");+ if (!response.ok) throw new Error();+ } catch {+ setStatus({+ isAvailable: false,+ error: "ollama not running on port 11434",+ });+ return;+ }+ break;- case "custom":- if (!settings.aiUrl) {- setStatus({- isAvailable: false,- error: "custom ai url not configured",- });- return;- }- break;- }+ case "screenpipe-cloud":+ if (!settings.user?.token) {+ setStatus({+ isAvailable: false,+ error: "login required for screenpipe cloud",+ });+ return;+ }+ break;- setStatus({ isAvailable: true, error: "" });- } catch (error) {- setStatus({- isAvailable: false,- error: "failed to check ai provider",- });- }- };+ case "custom":+ if (!settings.aiUrl) {+ setStatus({+ isAvailable: false,+ error: "custom ai url not configured",+ });+ return;+ }+ break;+ }- checkAiProvider();- }, [- settings.aiProviderType,- settings.openaiApiKey,- settings.aiUrl,- settings.user?.token,- ]);+ setStatus({ isAvailable: true, error: "" });+ } catch (error) {+ setStatus({+ isAvailable: false,+ error: "failed to check ai provider",+ });+ }+ };- return status;+ checkAiProvider();+ }, [+ settings?.aiProviderType,+ settings?.openaiApiKey,+ settings?.aiUrl,+ settings?.user?.token,+ ]);++ return status;}diff --git a/pipes/rewind/src/lib/hooks/use-app-name-suggestion.tsx b/pipes/rewind/src/lib/hooks/use-app-name-suggestion.tsxnew file mode 100644index 000000000..0b414b21c--- /dev/null+++ b/pipes/rewind/src/lib/hooks/use-app-name-suggestion.tsx@@ -0,0 +1,92 @@+import { useState, useCallback } from "react";++interface SearchResult {+ rank: number;+ app_name: string;+ window_name: string;+}++export function useAppNameSuggestion() {+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);++ const search = useCallback(async (searchText: string) => {+ try {+ setIsLoading(true);+ setError(null);+ const searchResults = await getAppandWindowByRank(searchText);+ return searchResults;+ } catch (err) {+ setError(+ err instanceof Error+ ? err+ : new Error("An error occurred during search"),+ );+ return [];+ } finally {+ setIsLoading(false);+ }+ }, []);++ return {+ isLoading,+ error,+ search,+ };+}++export async function getAppandWindowByRank(+ searchText: string,+ abortContorller?: AbortController,+): Promise<SearchResult[]> {+ // Input validation+ if (!searchText || typeof searchText !== "string") {+ throw new Error("Search text must be a non-empty string");+ }++ // Sanitize input: Remove any SQL special characters that could be used for injection+ const sanitizedText = searchText+ .replace(/[\0\x08\x09\x1a\n\r"'\\\%]/g, "")+ .replace(/\-\-/g, ""); // Remove SQL comment markers++ const query = `+ WITH RankedResults AS (+ SELECT+ rank,+ app_name,+ window_name,+ ROW_NUMBER() OVER (PARTITION BY window_name ORDER BY rank) as rn+ FROM ocr_text_fts+ WHERE text MATCH '${sanitizedText}'+ )+ SELECT+ rank,+ app_name,+ window_name+ FROM RankedResults+ WHERE rn = 1+ ORDER BY rank+ LIMIT 10+ `;++ try {+ const response = await fetch("http://localhost:3030/raw_sql", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ query }),+ signal: abortContorller?.signal,+ });++ if (!response.ok) {+ throw new Error(`HTTP error! status: ${response.status}`);+ }++ const data = await response.json();+ return data;+ } catch (error) {+ console.error("Error searching OCR text:", error);+ throw error;+ }+}diff --git a/pipes/rewind/src/lib/hooks/use-current-frame.tsx b/pipes/rewind/src/lib/hooks/use-current-frame.tsxindex 7baeb95ff..2d9b65391 100644--- a/pipes/rewind/src/lib/hooks/use-current-frame.tsx+++ b/pipes/rewind/src/lib/hooks/use-current-frame.tsx@@ -10,6 +10,7 @@ export const useCurrentFrame = (setCurrentIndex: (index: number) => void) => {const lastFramesLen = useRef<number>(0);useEffect(() => {+ console.log("current length", lastFramesLen);if (!currentFrame && frames.length) {setCurrentFrame(frames[lastFramesLen.current]);setCurrentIndex(lastFramesLen.current);diff --git a/pipes/rewind/src/lib/hooks/use-keyword-params.tsx b/pipes/rewind/src/lib/hooks/use-keyword-params.tsxnew file mode 100644index 000000000..398125a59--- /dev/null+++ b/pipes/rewind/src/lib/hooks/use-keyword-params.tsx@@ -0,0 +1,6 @@+import { useQueryStates } from "nuqs";+import { queryParser } from "../utils";++export const useKeywordParams = () => {+ return useQueryStates(queryParser, { throttleMs: 100 });+};diff --git a/pipes/rewind/src/lib/hooks/use-keyword-search-store.tsx b/pipes/rewind/src/lib/hooks/use-keyword-search-store.tsxnew file mode 100644index 000000000..a3871616a--- /dev/null+++ b/pipes/rewind/src/lib/hooks/use-keyword-search-store.tsx@@ -0,0 +1,295 @@+import { create } from "zustand";++export interface SearchMatch {+ frame_id: number;+ timestamp: string;+ text_positions: Array<{+ text: string;+ confidence: number;+ bounds: {+ left: number;+ top: number;+ width: number;+ height: number;+ };+ }>;+ app_name: string;+ window_name: string;+ confidence: number;+ text: string;+ url: string;+}++export interface SearchRequest {+ query: string;+ params: {+ offset?: number;+ limit?: number;+ start_time?: string;+ end_time?: string;+ fuzzy_match?: boolean;+ order?: "ascending" | "descending";+ app_names?: string[];+ };+}++export interface KeywordSearchState {+ searchResults: SearchMatch[];+ currentResultIndex: number;+ isSearching: boolean;+ searchQuery: string;+ error: string | null;+ lastRequest: SearchRequest | null;+ activeRequestId: string | null;+ currentAbortController: AbortController | null;++ searchKeywords: (+ query: string,+ options?: {+ limit?: number;+ offset?: number;+ include_context?: boolean;+ start_time?: Date;+ end_time?: Date;+ fuzzy_match?: boolean;+ order?: "ascending" | "descending";+ app_names?: string[];+ },+ signal?: AbortSignal,+ ) => Promise<void>;+ setCurrentResultIndex: (index: number) => void;+ resetSearch: () => void;+ nextResult: () => void;+ previousResult: () => void;+}++const fuzzy_default = false;+const offset_default = 0;++export const useKeywordSearchStore = create<KeywordSearchState>((set, get) => ({+ searchResults: [],+ currentResultIndex: -1,+ isSearching: false,+ searchQuery: "",+ error: null,+ lastRequest: null,+ activeRequestId: null,+ currentAbortController: null,++ searchKeywords: async (query, options = {}, signal?: AbortSignal) => {+ if (query.length === 0) return;++ const searchSignature = JSON.stringify({+ query,+ offset: options.offset || offset_default,+ limit: options.limit,+ start_time: options.start_time?.toISOString(),+ end_time: options.end_time?.toISOString(),+ fuzzy_match: options.fuzzy_match ?? fuzzy_default,+ order: options.order ?? "descending",+ app_names: options.app_names ?? [],+ });++ const { lastRequest } = get();+ if (+ lastRequest &&+ JSON.stringify({+ query: lastRequest.query,+ ...lastRequest.params,+ }) === searchSignature+ ) {+ return;+ }++ const { currentAbortController } = get();+ if (currentAbortController) {+ currentAbortController.abort();+ }++ const abortController = new AbortController();+ set({ currentAbortController: abortController });++ const combinedSignal = signal ? new AbortController() : abortController;++ if (signal) {+ signal.addEventListener("abort", () => combinedSignal.abort());+ abortController.signal.addEventListener("abort", () =>+ combinedSignal.abort(),+ );+ }++ const requestId = Math.random().toString(36).substring(7);+ const isInitialSearch = !options.offset || options.offset === 0;++ if (isInitialSearch) {+ set({+ searchResults: [],+ currentResultIndex: -1,+ activeRequestId: requestId,+ isSearching: true,+ error: null,+ });+ } else {+ set((state) => ({+ ...state,+ activeRequestId: requestId,+ isSearching: true,+ error: null,+ }));+ }++ const { searchResults } = get();++ const searchRequest: SearchRequest = {+ query,+ params: {+ offset: options.offset || offset_default,+ limit: options.limit,+ start_time: options.start_time?.toISOString(),+ end_time: options.end_time?.toISOString(),+ fuzzy_match: options.fuzzy_match ?? fuzzy_default,+ order: options.order ?? "descending",+ app_names: options.app_names ?? [],+ },+ };++ try {+ const params = new URLSearchParams({+ query,+ offset: (options.offset ?? 0).toString(),+ include_context: (options.include_context ?? false).toString(),+ fuzzy_match: (options.fuzzy_match ?? fuzzy_default).toString(),+ });++ if (options.app_names) {+ params.append("app_names", options.app_names.join(","));+ }++ if (options.start_time) {+ params.append("start_time", options.start_time.toISOString());+ }++ if (options.end_time) {+ const now = new Date();+ const end = options.end_time;++ if (+ end.getDate() === now.getDate() &&+ end.getMonth() === now.getMonth() &&+ end.getFullYear() === now.getFullYear()+ ) {+ const fiveMinutesAgo = new Date(now.getTime() - 10 * 60000);+ params.append("end_time", fiveMinutesAgo.toISOString());+ } else {+ params.append("end_time", end.toISOString());+ }+ } else {+ const now = new Date();+ const fiveMinutesAgo = new Date(now.getTime() - 10 * 60000);+ fiveMinutesAgo.setSeconds(0, 0);+ params.append("end_time", fiveMinutesAgo.toISOString());+ }++ if (options.order) {+ params.append("order", options.order);+ }++ if (options.limit) {+ params.append("limit", options.limit.toString());+ }++ const response = await fetch(+ `http://localhost:3030/search/keyword?${params}`,+ { signal: combinedSignal.signal },+ );++ if (!response.ok) {+ throw new Error("Search request failed");+ }++ const results = await response.json();++ if (get().activeRequestId === requestId) {+ if (!isInitialSearch) {+ const existingFrameIds = new Set(+ searchResults.map((r) => r.frame_id),+ );+ const uniqueNewResults = results.filter(+ (result: SearchMatch) => !existingFrameIds.has(result.frame_id),+ );++ set({+ searchResults: [...searchResults, ...uniqueNewResults],+ currentResultIndex: get().currentResultIndex,+ searchQuery: query,+ isSearching: false,+ lastRequest: searchRequest,+ currentAbortController: null,+ });+ } else {+ set({+ searchResults: results,+ currentResultIndex: results.length > 0 ? 0 : -1,+ searchQuery: query,+ isSearching: false,+ lastRequest: searchRequest,+ currentAbortController: null,+ });+ }+ }+ } catch (error) {+ if (error instanceof Error && error.name === "AbortError") {+ return;+ }++ if (get().activeRequestId === requestId) {+ set({+ error: error instanceof Error ? error.message : "Search failed",+ isSearching: false,+ currentAbortController: null,+ });+ }+ }+ },++ setCurrentResultIndex: (index) => {+ set({ currentResultIndex: index });+ },++ resetSearch: () => {+ const { currentAbortController } = get();+ if (currentAbortController) {+ currentAbortController.abort();+ }++ set({+ searchResults: [],+ currentResultIndex: -1,+ isSearching: false,+ searchQuery: "",+ error: null,+ lastRequest: null,+ activeRequestId: null,+ currentAbortController: null,+ });+ },++ nextResult: () => {+ const { searchResults, currentResultIndex } = get();+ if (searchResults.length === 0) return;++ const nextIndex = (currentResultIndex + 1) % searchResults.length;+ set({ currentResultIndex: nextIndex });+ },++ previousResult: () => {+ const { searchResults, currentResultIndex } = get();+ if (searchResults.length === 0) return;++ const prevIndex =+ currentResultIndex - 1 < 0+ ? searchResults.length - 1+ : currentResultIndex - 1;+ set({ currentResultIndex: prevIndex });+ },+}));diff --git a/pipes/rewind/src/lib/hooks/use-settings.tsx b/pipes/rewind/src/lib/hooks/use-settings.tsxindex 1e9a327b9..e431a8bea 100644--- a/pipes/rewind/src/lib/hooks/use-settings.tsx+++ b/pipes/rewind/src/lib/hooks/use-settings.tsx@@ -1,97 +1,8 @@-"use client";--import { useState, useEffect } from "react";-import { getDefaultSettings, type Settings } from "@screenpipe/browser";+import { useContext } from "react";+import { SettingsContext } from "@/components/settings-provider";export function useSettings() {- const defaultSettings = getDefaultSettings();-- const [settings, setSettings] = useState<Settings>(defaultSettings);- const [loading, setLoading] = useState(false);- const [error, setError] = useState<Error | null>(null);-- useEffect(() => {- const loadSettings = async () => {- setLoading(true);- try {- const response = await fetch("/api/settings");- const data = await response.json();- setSettings({ ...defaultSettings, ...data });- } catch (err) {- setError(err as Error);- } finally {- setLoading(false);- }- };-- // Initial load- loadSettings();-- // Refresh on window focus- const onFocus = () => loadSettings();- window.addEventListener("focus", onFocus);-- // Optional: periodic refresh every 30s- const interval = setInterval(loadSettings, 30000);-- return () => {- window.removeEventListener("focus", onFocus);- clearInterval(interval);- };- }, []);-- const updateSetting = async <T extends keyof Settings>(- key: T,- value: Settings[T]- ) => {- try {- await fetch("/api/settings", {- method: "PUT",- body: JSON.stringify({ key, value }),- });- setSettings((prev) => ({ ...prev, [key]: value }));- } catch (err) {- setError(err as Error);- }- };-- const updateSettings = async (newSettings: Partial<Settings>) => {- try {- await fetch("/api/settings", {- method: "PUT",- body: JSON.stringify({ value: newSettings, isPartialUpdate: true }),- });- setSettings((prev) => ({ ...prev, ...newSettings }));- } catch (err) {- setError(err as Error);- }- };-- const resetSettings = async (settingKey?: keyof Settings) => {- try {- await fetch("/api/settings", {- method: "PUT",- body: JSON.stringify({ reset: true, key: settingKey }),- });- if (settingKey) {- setSettings((prev) => ({- ...prev,- [settingKey]: defaultSettings[settingKey],- }));- } else {- setSettings(defaultSettings);- }- } catch (err) {- setError(err as Error);- }- };+ const settingsProps = useContext(SettingsContext);- return {- settings,- loading,- error,- updateSetting,- updateSettings,- resetSettings,- };+ return { ...settingsProps };}diff --git a/pipes/rewind/src/lib/hooks/use-sql-autocomplete.tsx b/pipes/rewind/src/lib/hooks/use-sql-autocomplete.tsxindex 7db3de855..f9b0bf162 100644--- a/pipes/rewind/src/lib/hooks/use-sql-autocomplete.tsx+++ b/pipes/rewind/src/lib/hooks/use-sql-autocomplete.tsx@@ -1,30 +1,30 @@import { useState, useEffect, useCallback } from "react";-interface AutocompleteItem {- name: string;- count: number;+export interface AutocompleteItem {+ name: string;+ count: number;}const CACHE_DURATION = 5 * 60 * 1000; // 5 minutesconst cache: Record<string, { data: AutocompleteItem[]; timestamp: number }> =- {};+ {};export function useSqlAutocomplete(type: "app" | "window") {- const [items, setItems] = useState<AutocompleteItem[]>([]);- const [isLoading, setIsLoading] = useState(false);+ const [items, setItems] = useState<AutocompleteItem[]>([]);+ const [isLoading, setIsLoading] = useState(false);- const fetchItems = useCallback(async () => {- setIsLoading(true);- try {- const cachedData = cache[type];- if (cachedData && Date.now() - cachedData.timestamp < CACHE_DURATION) {- setItems(cachedData.data);- } else {- const query = `+ const fetchItems = useCallback(async () => {+ setIsLoading(true);+ try {+ const cachedData = cache[type];+ if (cachedData && Date.now() - cachedData.timestamp < CACHE_DURATION) {+ setItems(cachedData.data);+ } else {+ const query = `SELECT ${- type === "app" ? "ocr.app_name" : "ocr.window_name"- } as name, COUNT(*) as count+ type === "app" ? "ocr.app_name" : "ocr.window_name"+ } as name, COUNT(*) as countFROM ocr_text ocrJOIN frames f ON ocr.frame_id = f.idWHERE f.timestamp > datetime('now', '-7 days')@@ -32,30 +32,30 @@ export function useSqlAutocomplete(type: "app" | "window") {ORDER BY count DESCLIMIT 100`;- const response = await fetch("http://localhost:3030/raw_sql", {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({ query }),- });- if (!response.ok) {- throw new Error(`HTTP error! status: ${response.status}`);- }- const result = await response.json();- setItems(result);- cache[type] = { data: result, timestamp: Date.now() };- }- } catch (error) {- console.error("failed to fetch items:", error);- } finally {- setIsLoading(false);- }- }, [type]);+ const response = await fetch("http://localhost:3030/raw_sql", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ query }),+ });+ if (!response.ok) {+ throw new Error(`HTTP error! status: ${response.status}`);+ }+ const result = await response.json();+ setItems(result);+ cache[type] = { data: result, timestamp: Date.now() };+ }+ } catch (error) {+ console.error("failed to fetch items:", error);+ } finally {+ setIsLoading(false);+ }+ }, [type]);- useEffect(() => {- fetchItems();- }, [fetchItems]);+ useEffect(() => {+ fetchItems();+ }, [fetchItems]);- return { items, isLoading };+ return { items, isLoading };}diff --git a/pipes/rewind/src/lib/hooks/use-suggestion.tsx b/pipes/rewind/src/lib/hooks/use-suggestion.tsxnew file mode 100644index 000000000..b5a40bdca--- /dev/null+++ b/pipes/rewind/src/lib/hooks/use-suggestion.tsx@@ -0,0 +1,153 @@+import { useState, useEffect } from "react";+import { useSettings } from "./use-settings";+import OpenAI from "openai";+// import { fetchAppAndWindowNames } from "../raw_sql_queries";+import { z } from "zod";+import { zodResponseFormat } from "openai/helpers/zod";+import { parser } from "../keyword-parser";+import { getAppandWindowByRank } from "./use-app-name-suggestion";++interface AppStats {+ apps: Record<string, number>;+ windows: Record<string, number>;+}++export function useSuggestions(keywordString: string) {+ const [suggestions, setSuggestions] = useState<string[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const { settings } = useSettings();++ useEffect(() => {+ const abortController = new AbortController();++ setSuggestions([]);+ const generateSuggestions = async () => {+ if (keywordString.length < 3) {+ setIsLoading(false);+ setError(null);+ setSuggestions([]);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const keywords = parser.parse(keywordString).keywords;++ if (!keywords.length) {+ setSuggestions([]);+ return;+ }++ const appData = await getAppandWindowByRank(+ keywords.join(" "),+ abortController,+ );++ const appStats: AppStats = {+ apps: {},+ windows: {},+ };++ appData.forEach((item: { app_name: string; window_name: string }) => {+ if (item.app_name) {+ appStats.apps[item.app_name] =+ (appStats.apps[item.app_name] || 0) + 1;+ }+ if (item.window_name) {+ appStats.windows[item.window_name] =+ (appStats.windows[item.window_name] || 0) + 1;+ }+ });++ if (+ Object.keys(appStats.apps).length === 0 &&+ Object.keys(appStats.windows).length === 0+ ) {+ setSuggestions([]);+ return;+ }++ const openai = new OpenAI({+ apiKey:+ settings?.aiProviderType === "screenpipe-cloud"+ ? settings?.user?.token+ : settings?.openaiApiKey,+ baseURL: settings?.aiUrl,+ dangerouslyAllowBrowser: true,+ });++ const newPrompt = `Generate 5 natural search suggestions strictly based on the most commonly used apps and activities found in the provided user data.++ Use the app statistics as a key reference:+ apps: ${JSON.stringify(appStats.apps)}+ windows: ${JSON.stringify(appStats.windows)}++ Instructions:+ - Do not generate suggestions beyond the scope of the provided data.+ - Ensure specificity and variety in the search suggestions by considering different user activities.+ - Use app interactions and window history to infer relevant searches.+ - Suggestions should align naturally with the user's existing usage patterns.+ - if no apps and windows are given then just return empty array.+`;++ const response = await openai.chat.completions.create(+ {+ model: settings?.aiModel || "",+ messages: [+ {+ role: "system",+ content:+ "You are an AI assistant helping generate search suggestions based on user's app usage data.",+ },+ {+ role: "user",+ content: newPrompt,+ },+ ],+ response_format: zodResponseFormat(+ z.object({ suggestions: z.array(z.string()) }),+ "user_data_suggestions",+ ),+ },+ {+ signal: abortController.signal,+ },+ );++ const content = response.choices[0]?.message?.content;+ if (content) {+ const result = JSON.parse(content);+ setSuggestions(result.suggestions);+ }++ setIsLoading(false);+ } catch (err) {+ if (err instanceof Error) {+ // Only set error if it's not an abort error+ if (err.name !== "AbortError") {+ setError(err.message);+ setSuggestions([]);+ }+ // Always set loading to false for both abort and other errors+ setIsLoading(false);+ } else {+ setError("Unable to generate suggestions. Please try again.");+ setSuggestions([]);+ setIsLoading(false);+ }+ }+ };++ generateSuggestions();++ return () => {+ setIsLoading(false);+ abortController.abort();+ };+ }, [keywordString]);++ return { suggestions, isLoading, error };+}diff --git a/pipes/rewind/src/lib/keyword-parser.ts b/pipes/rewind/src/lib/keyword-parser.tsnew file mode 100644index 000000000..cde9bb69a--- /dev/null+++ b/pipes/rewind/src/lib/keyword-parser.ts@@ -0,0 +1,236 @@+import { removeStopwords, eng } from "stopword";++interface KeywordResult {+ keywords: string[];+}++class KeywordParser {+ private additionalStopWords: Set<string>;++ constructor() {+ // Additional stop words that might be missed by the library+ this.additionalStopWords = new Set([+ // Question words and related terms+ "when",+ "where",+ "what",+ "which",+ "who",+ "whom",+ "whose",+ "why",+ "how",++ // Negations and quantities+ "not",+ "none",+ "no",+ "nothing",+ "never",+ "neither",+ "nor",++ // Common verbs and auxiliaries+ "am",+ "is",+ "are",+ "was",+ "were",+ "be",+ "being",+ "been",+ "have",+ "has",+ "had",+ "having",+ "do",+ "does",+ "did",+ "doing",+ "can",+ "could",+ "will",+ "would",+ "shall",+ "should",+ "may",+ "might",+ "must",++ // Prepositions and articles+ "in",+ "on",+ "at",+ "to",+ "for",+ "with",+ "by",+ "from",+ "up",+ "down",+ "into",+ "onto",+ "upon",+ "under",+ "below",+ "above",+ "over",+ "through",+ "after",+ "before",+ "during",+ "within",+ "throughout",++ // Conjunctions+ "and",+ "or",+ "but",+ "nor",+ "yet",+ "so",+ "although",+ "though",+ "while",+ "if",+ "unless",+ "until",+ "because",++ // Pronouns+ "i",+ "me",+ "my",+ "mine",+ "myself",+ "you",+ "your",+ "yours",+ "yourself",+ "he",+ "him",+ "his",+ "himself",+ "she",+ "her",+ "hers",+ "herself",+ "it",+ "its",+ "itself",+ "we",+ "us",+ "our",+ "ours",+ "ourselves",+ "they",+ "them",+ "their",+ "theirs",+ "themselves",++ // Common adverbs+ "very",+ "really",+ "quite",+ "rather",+ "somewhat",+ "just",+ "only",+ "even",+ "still",+ "again",+ "too",+ "also",+ "perhaps",+ "maybe",+ "here",+ "there",+ "now",+ "then",+ "always",+ "never",++ // Others+ "like",+ "want",+ "wanted",+ "wants",+ "need",+ "needs",+ "needed",+ "get",+ "gets",+ "got",+ "getting",+ "make",+ "makes",+ "made",+ "making",+ "use",+ "uses",+ "used",+ "using",+ "way",+ "ways",+ "thing",+ "things",+ "etc",+ "etc.",+ "yeah",+ "yes",+ "no",+ "ok",+ "okay",+ "would",+ "could",+ "should",+ "shall",+ "able",+ "unable",+ "lot",+ "lots",+ "much",+ "many",+ "several",+ "few",+ "little",+ "every",+ "each",+ "any",+ "some",+ "all",+ ]);+ }++ private cleanText(text: string): string {+ // Convert to lowercase and remove special characters+ return text.toLowerCase().replace(/[^\w\s]/g, "");+ }++ private tokenize(text: string): string[] {+ // Split text into words+ return text.split(/\s+/).filter((word) => word.length > 0);+ }++ public parse(text: string): KeywordResult {+ const cleanedText = this.cleanText(text);+ const tokens = this.tokenize(cleanedText);++ // First remove library stopwords+ let keywords = removeStopwords(tokens, [+ ...eng,+ ...this.additionalStopWords,+ ]);++ // Filter out single characters only+ keywords = keywords.filter((word) => word.length > 1);++ // Remove duplicates+ const uniqueKeywords = Array.from(new Set(keywords));++ return { keywords: uniqueKeywords };+ }+}++export const parser = new KeywordParser();diff --git a/pipes/rewind/src/lib/raw_sql_queries.ts b/pipes/rewind/src/lib/raw_sql_queries.tsnew file mode 100644index 000000000..539cdc5be--- /dev/null+++ b/pipes/rewind/src/lib/raw_sql_queries.ts@@ -0,0 +1,42 @@+export async function fetchAppAndWindowNames(+ keywords: string[],+ signal?: AbortSignal,+) {+ const conditions = keywords+ .map((k) => {+ const pattern = `%${k}%`;+ return `(+ o.text LIKE '${pattern}' AND+ (o.window_name LIKE '${pattern}' OR o.app_name LIKE '${pattern}')+ )`;+ })+ .join(" OR ");++ const sql = `+ SELECT DISTINCT+ o.app_name,+ o.window_name+ FROM frames f+ JOIN ocr_text o ON f.id = o.frame_id+ WHERE ${conditions}+ ORDER BY f.timestamp DESC+ LIMIT 100+ `;++ const response = await fetch("http://localhost:3030/raw_sql", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ query: sql }),+ signal,+ });++ if (!response.ok) {+ throw new Error("Failed to execute raw SQL query");+ }++ const res = await response.json();+ console.log(res);+ return res;+}diff --git a/pipes/rewind/src/lib/utils.ts b/pipes/rewind/src/lib/utils.tsindex 1dcf56583..d0e96c1c4 100644--- a/pipes/rewind/src/lib/utils.ts+++ b/pipes/rewind/src/lib/utils.ts@@ -2,6 +2,13 @@ import { ContentItem } from "@screenpipe/js";import { clsx, type ClassValue } from "clsx";import { twMerge } from "tailwind-merge";import levenshtein from "js-levenshtein";+import {+ createSerializer,+ inferParserType,+ parseAsArrayOf,+ parseAsIsoDateTime,+ parseAsString,+} from "nuqs";export function cn(...inputs: ClassValue[]) {return twMerge(clsx(inputs));@@ -58,3 +65,14 @@ export function stringToColor(str: string): string {}return color;}++export const queryParser = {+ query: parseAsString,+ start_time: parseAsIsoDateTime,+ end_time: parseAsIsoDateTime,+ apps: parseAsArrayOf(parseAsString),+};++export const querySerializer = createSerializer(queryParser);++export type QueryParser = inferParserType<typeof queryParser>;diff --git a/pipes/rewind/tailwind.config.ts b/pipes/rewind/tailwind.config.tsindex 9a58f7ad4..5ec9e4e2d 100644--- a/pipes/rewind/tailwind.config.ts+++ b/pipes/rewind/tailwind.config.ts@@ -1,84 +1,96 @@import type { Config } from "tailwindcss";export default {- darkMode: ["class"],- content: [- "./src/pages/**/*.{js,ts,jsx,tsx,mdx}",- "./src/components/**/*.{js,ts,jsx,tsx,mdx}",- "./src/app/**/*.{js,ts,jsx,tsx,mdx}",- ],- theme: {- extend: {- colors: {- background: 'hsl(var(--background))',- foreground: 'hsl(var(--foreground))',- card: {- DEFAULT: 'hsl(var(--card))',- foreground: 'hsl(var(--card-foreground))'- },- popover: {- DEFAULT: 'hsl(var(--popover))',- foreground: 'hsl(var(--popover-foreground))'- },- primary: {- DEFAULT: 'hsl(var(--primary))',- foreground: 'hsl(var(--primary-foreground))'- },- secondary: {- DEFAULT: 'hsl(var(--secondary))',- foreground: 'hsl(var(--secondary-foreground))'- },- muted: {- DEFAULT: 'hsl(var(--muted))',- foreground: 'hsl(var(--muted-foreground))'- },- accent: {- DEFAULT: 'hsl(var(--accent))',- foreground: 'hsl(var(--accent-foreground))'- },- destructive: {- DEFAULT: 'hsl(var(--destructive))',- foreground: 'hsl(var(--destructive-foreground))'- },- border: 'hsl(var(--border))',- input: 'hsl(var(--input))',- ring: 'hsl(var(--ring))',- chart: {- '1': 'hsl(var(--chart-1))',- '2': 'hsl(var(--chart-2))',- '3': 'hsl(var(--chart-3))',- '4': 'hsl(var(--chart-4))',- '5': 'hsl(var(--chart-5))'- }- },- borderRadius: {- lg: 'var(--radius)',- md: 'calc(var(--radius) - 2px)',- sm: 'calc(var(--radius) - 4px)'- },- keyframes: {- 'accordion-down': {- from: {- height: '0'- },- to: {- height: 'var(--radix-accordion-content-height)'- }- },- 'accordion-up': {- from: {- height: 'var(--radix-accordion-content-height)'- },- to: {- height: '0'- }- }- },- animation: {- 'accordion-down': 'accordion-down 0.2s ease-out',- 'accordion-up': 'accordion-up 0.2s ease-out'- }- }- },- plugins: [require("tailwindcss-animate")],+ darkMode: ["class"],+ content: [+ "./src/pages/**/*.{js,ts,jsx,tsx,mdx}",+ "./src/components/**/*.{js,ts,jsx,tsx,mdx}",+ "./src/app/**/*.{js,ts,jsx,tsx,mdx}",+ ],+ theme: {+ extend: {+ colors: {+ background: "hsl(var(--background))",+ foreground: "hsl(var(--foreground))",+ neutral: {+ 50: "#f8f9fa",+ 100: "#f1f3f5",+ 200: "#e9ecef",+ 300: "#dee2e6",+ 400: "#ced4da",+ 500: "#adb5bd",+ 600: "#868e96",+ 700: "#495057",+ 800: "#343a40",+ 900: "#212529",+ },+ card: {+ DEFAULT: "hsl(var(--card))",+ foreground: "hsl(var(--card-foreground))",+ },+ popover: {+ DEFAULT: "hsl(var(--popover))",+ foreground: "hsl(var(--popover-foreground))",+ },+ primary: {+ DEFAULT: "hsl(var(--primary))",+ foreground: "hsl(var(--primary-foreground))",+ },+ secondary: {+ DEFAULT: "hsl(var(--secondary))",+ foreground: "hsl(var(--secondary-foreground))",+ },+ muted: {+ DEFAULT: "hsl(var(--muted))",+ foreground: "hsl(var(--muted-foreground))",+ },+ accent: {+ DEFAULT: "hsl(var(--accent))",+ foreground: "hsl(var(--accent-foreground))",+ },+ destructive: {+ DEFAULT: "hsl(var(--destructive))",+ foreground: "hsl(var(--destructive-foreground))",+ },+ border: "hsl(var(--border))",+ input: "hsl(var(--input))",+ ring: "hsl(var(--ring))",+ chart: {+ "1": "hsl(var(--chart-1))",+ "2": "hsl(var(--chart-2))",+ "3": "hsl(var(--chart-3))",+ "4": "hsl(var(--chart-4))",+ "5": "hsl(var(--chart-5))",+ },+ },+ borderRadius: {+ lg: "var(--radius)",+ md: "calc(var(--radius) - 2px)",+ sm: "calc(var(--radius) - 4px)",+ },+ keyframes: {+ "accordion-down": {+ from: {+ height: "0",+ },+ to: {+ height: "var(--radix-accordion-content-height)",+ },+ },+ "accordion-up": {+ from: {+ height: "var(--radix-accordion-content-height)",+ },+ to: {+ height: "0",+ },+ },+ },+ animation: {+ "accordion-down": "accordion-down 0.2s ease-out",+ "accordion-up": "accordion-up 0.2s ease-out",+ },+ },+ },+ plugins: [require("tailwindcss-animate")],} satisfies Config;diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rsindex fdef06b23..3ece39499 100644--- a/screenpipe-server/src/db.rs+++ b/screenpipe-server/src/db.rs@@ -21,8 +21,9 @@ use tokio::time::{timeout, Duration as TokioDuration};use zerocopy::AsBytes;use crate::db_types::{- AudioChunksResponse, AudioEntry, AudioResult, AudioResultRaw, FrameData, OCREntry, OCRResult,- OCRResultRaw, Speaker, TagContentType,+ AudioChunksResponse, AudioEntry, AudioResult, AudioResultRaw, FrameData, FrameRow, OCREntry,+ OCRResult, OCRResultRaw, OcrTextBlock, Order, SearchMatch, Speaker, TagContentType, TextBounds,+ TextPosition,};use crate::db_types::{ContentType, UiContent};use crate::db_types::{SearchResult, TimeSeriesChunk};@@ -1990,6 +1991,7 @@ impl DatabaseManager {frames.timestamp,video_chunks.file_path,frames.offset_index,+ frames.name as frame_name,ocr_text.app_name,ocr_text.ocr_engine,ocr_text.window_name,@@ -2146,4 +2148,175 @@ impl DatabaseManager {}}}++ #[allow(clippy::too_many_arguments)]+ pub async fn search_with_text_positions(+ &self,+ query: &str,+ limit: u32,+ offset: u32,+ start_time: Option<DateTime<Utc>>,+ end_time: Option<DateTime<Utc>>,+ fuzzy_match: bool,+ order: Order,+ app_names: Option<Vec<String>>,+ ) -> Result<Vec<SearchMatch>, sqlx::Error> {+ let mut conditions = Vec::new();+ let mut owned_conditions = Vec::new();++ if start_time.is_some() {+ conditions.push("f.timestamp >= ?");+ }+ if end_time.is_some() {+ conditions.push("f.timestamp <= ?");+ }++ // Add app names condition if provided+ if let Some(apps) = &app_names {+ if !apps.is_empty() {+ let placeholders = vec!["?"; apps.len()].join(",");+ let app_condition = format!("o.app_name IN ({})", placeholders);+ owned_conditions.push(app_condition);+ conditions.push(owned_conditions.last().unwrap().as_str());+ }+ }++ // Create an indexed subquery for FTS matching+ let search_condition = if !query.is_empty() {+ let fts_match = if fuzzy_match {+ query+ .split_whitespace()+ .map(|word| format!("{}*", word))+ .collect::<Vec<_>>()+ .join(" OR ")+ } else {+ query.to_string()+ };+ conditions.push(+ "f.id IN (SELECT frame_id FROM ocr_text_fts WHERE text MATCH ? ORDER BY rank)",+ );+ fts_match+ } else {+ String::new()+ };++ let sql = format!(+ r#"+SELECT+ f.id,+ f.timestamp,+ f.browser_url as url,+ o.app_name,+ o.window_name,+ o.text as ocr_text,+ o.text_json+FROM frames f+INNER JOIN ocr_text o ON f.id = o.frame_id+WHERE {}+ORDER BY f.timestamp {}+LIMIT ? OFFSET ?+"#,+ if conditions.is_empty() {+ "1=1".to_string()+ } else {+ conditions.join(" AND ")+ },+ match order {+ Order::Ascending => "ASC",+ Order::Descending => "DESC",+ }+ );++ let mut query_builder = sqlx::query_as::<_, FrameRow>(&sql);++ // Bind timestamp parameters first+ if let Some(start) = start_time {+ query_builder = query_builder.bind(start);+ }+ if let Some(end) = end_time {+ query_builder = query_builder.bind(end);+ }++ // Bind app names if provided+ if let Some(apps) = app_names {+ if !apps.is_empty() {+ for app in apps {+ query_builder = query_builder.bind(app);+ }+ }+ }++ // Bind search condition if query is not empty+ if !query.is_empty() {+ query_builder = query_builder.bind(&search_condition);+ }++ // Bind limit and offset+ query_builder = query_builder.bind(limit as i64).bind(offset as i64);++ let rows = query_builder.fetch_all(&self.pool).await?;++ Ok(rows+ .iter()+ .map(|row| {+ let positions = if !query.is_empty() {+ let ocr_blocks: Vec<OcrTextBlock> =+ serde_json::from_str(&row.text_json).unwrap_or_default();+ find_matching_positions(&ocr_blocks, query)+ } else {+ Vec::new()+ };++ SearchMatch {+ frame_id: row.id,+ timestamp: row.timestamp,+ text_positions: positions.clone(),+ app_name: row.app_name.clone(),+ window_name: row.window_name.clone(),+ confidence: calculate_confidence(&positions),+ text: row.ocr_text.clone(),+ url: row.url.clone(),+ }+ })+ .collect())+ }+}++pub fn find_matching_positions(blocks: &[OcrTextBlock], query: &str) -> Vec<TextPosition> {+ let query_lower = query.to_lowercase();+ let query_words: Vec<&str> = query_lower.split_whitespace().collect();++ blocks+ .iter()+ .filter_map(|block| {+ let text_lower = block.text.to_lowercase();++ // Check for exact match or any word match+ let matches = text_lower.contains(&query_lower)+ || query_words.iter().any(|&word| text_lower.contains(word));++ if matches {+ Some(TextPosition {+ text: block.text.clone(),+ confidence: block.conf.parse::<f32>().unwrap_or(0.0),+ bounds: TextBounds {+ left: block.left.parse::<f32>().unwrap_or(0.0),+ top: block.top.parse::<f32>().unwrap_or(0.0),+ width: block.width.parse::<f32>().unwrap_or(0.0),+ height: block.height.parse::<f32>().unwrap_or(0.0),+ },+ })+ } else {+ None+ }+ })+ .collect()+}++fn calculate_confidence(positions: &[TextPosition]) -> f32 {+ if positions.is_empty() {+ return 0.0;+ }++ positions.iter().map(|pos| pos.confidence).sum::<f32>() / positions.len() as f32}diff --git a/screenpipe-server/src/db_types.rs b/screenpipe-server/src/db_types.rsindex 912d1990f..a065468e7 100644--- a/screenpipe-server/src/db_types.rs+++ b/screenpipe-server/src/db_types.rs@@ -201,3 +201,67 @@ pub struct AudioChunksResponse {pub file_path: String,pub timestamp: DateTime<Utc>,}++#[derive(Debug, Serialize, Deserialize)]+pub struct OcrTextBlock {+ pub block_num: String,+ pub conf: String,+ pub page_num: String,+ pub left: String,+ pub height: String,+ pub level: String,+ pub text: String,+ pub par_num: String,+ pub top: String,+ pub word_num: String,+ pub width: String,+ pub line_num: String,+}++#[derive(Debug, Serialize, Clone)]+pub struct TextPosition {+ pub text: String,+ pub confidence: f32,+ pub bounds: TextBounds,+}++#[derive(Debug, Serialize, Clone)]+pub struct TextBounds {+ pub left: f32,+ pub top: f32,+ pub width: f32,+ pub height: f32,+}++#[derive(Serialize)]+pub struct SearchMatch {+ pub frame_id: i64,+ pub timestamp: DateTime<Utc>,+ pub text_positions: Vec<TextPosition>,+ pub app_name: String,+ pub window_name: String,+ pub confidence: f32,+ // pub context: Option<String>,+ pub text: String,+ pub url: String,+}++#[derive(Debug, Serialize, Deserialize, FromRow)]+pub struct FrameRow {+ pub id: i64,+ pub timestamp: DateTime<Utc>,+ pub url: String,+ pub app_name: String,+ pub window_name: String,+ pub ocr_text: String,+ pub text_json: String,+}++#[derive(Deserialize, PartialEq, Default)]+pub enum Order {+ #[serde(rename = "ascending")]+ Ascending,+ #[serde(rename = "descending")]+ #[default]+ Descending,+}diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex a1b48a0f7..9d9c2b906 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -21,7 +21,7 @@ use image::ImageFormat::{self};use screenpipe_events::{send_event, subscribe_to_all_events, Event as ScreenpipeEvent};use crate::{- db_types::{ContentType, FrameData, SearchResult, Speaker, TagContentType},+ db_types::{ContentType, FrameData, Order, SearchMatch, SearchResult, Speaker, TagContentType},pipe_manager::PipeManager,video::{finish_ffmpeg_process, start_ffmpeg_process, write_frame_to_ffmpeg, MAX_FPS},video_cache::{AudioEntry, DeviceFrame, FrameCache, FrameMetadata, TimeSeriesFrame},@@ -1381,20 +1381,6 @@ struct InputControlResponse {success: bool,}-#[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 {@@ -2066,6 +2052,7 @@ pub fn create_router() -> Router<Arc<AppState>> {.route("/ws/events", get(ws_events_handler)).route("/semantic-search", get(semantic_search_handler)).route("/frames/:frame_id", get(get_frame_data))+ .route("/search/keyword", get(keyword_search_handler))// .route("/vision/start", post(start_vision_device))// .route("/vision/stop", post(stop_vision_device))// .route("/audio/restart", post(restart_audio_devices))@@ -2080,6 +2067,61 @@ pub fn create_router() -> Router<Arc<AppState>> {router}+async fn keyword_search_handler(+ Query(query): Query<KeywordSearchRequest>,+ State(state): State<Arc<AppState>>,+) -> Result<JsonResponse<Vec<SearchMatch>>, (StatusCode, JsonResponse<Value>)> {+ let matches = state+ .db+ .search_with_text_positions(+ &query.query,+ query.limit,+ query.offset,+ query.start_time,+ query.end_time,+ query.fuzzy_match,+ query.order,+ query.app_names,+ )+ .await+ .map_err(|e| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ JsonResponse(json!({"error": e.to_string()})),+ )+ })?;++ Ok(JsonResponse(matches))+}++fn from_comma_separated_string<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>+where+ D: Deserializer<'de>,+{+ let s: Option<String> = Option::deserialize(deserializer)?;+ Ok(s.map(|s| s.split(',').map(String::from).collect()))+}++#[derive(Deserialize)]+pub struct KeywordSearchRequest {+ query: String,+ #[serde(default = "default_limit")]+ limit: u32,+ #[serde(default)]+ offset: u32,+ #[serde(default)]+ start_time: Option<DateTime<Utc>>,+ #[serde(default)]+ end_time: Option<DateTime<Utc>>,+ #[serde(default)]+ fuzzy_match: bool,+ #[serde(default)]+ order: Order,+ #[serde(default)]+ #[serde(deserialize_with = "from_comma_separated_string")]+ app_names: Option<Vec<String>>,+}+pub async fn get_frame_data(State(state): State<Arc<AppState>>,Path(frame_id): Path<i64>,diff --git a/screenpipe-server/src/video_utils.rs b/screenpipe-server/src/video_utils.rsindex d64bff640..2e2e56eaf 100644--- a/screenpipe-server/src/video_utils.rs+++ b/screenpipe-server/src/video_utils.rs@@ -515,7 +515,15 @@ 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 source_fps = match get_video_fps(&ffmpeg_path, &file_path).await {+ Ok(fps) => fps,+ Err(e) => {+ error!("failed to get video fps, using default 1fps: {}", e);+ 1.0+ }+ };++ let offset_seconds = offset_index as f64 * source_fps;let offset_str = format!("{:.3}", offset_seconds);// Create a temporary directory for frames if it doesn't exist@@ -527,9 +535,10 @@ pub async fn extract_frame_from_video(file_path: &str, offset_index: i64) -> Reslet output_path = frames_dir.join(&frame_filename);debug!(- "extracting frame from {} at offset {} to {}",+ "extracting frame from {} at offset {} and fps {} to {}",file_path,offset_str,+ source_fps,output_path.display());@@ -541,13 +550,18 @@ pub async fn extract_frame_from_video(file_path: &str, offset_index: i64) -> Res"-i",file_path,"-vf",- "scale=iw*0.75:ih*0.75",+ "scale=iw*0.75:ih*0.75,format=yuvj420p", // Add format conversion"-vframes","1","-c:v","mjpeg",+ "-strict",+ "unofficial", // Add strict compliance setting+ "-pix_fmt",+ "yuvj420p", // Ensure proper pixel format"-q:v","10",+ "-y", // Force overwriteoutput_path.to_str().unwrap(),]).stdout(std::process::Stdio::piped())