Skip to content

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

fix: memory pipe now avoid showing recent memories, and give you some AI descriptions (make sure to reinstall it)

Louis Beaumont6874e4c6dd19
diff --git a/pipes/memories/src/components/memories-gallery.tsx b/pipes/memories/src/components/memories-gallery.tsx
index 727b556f8..80eafbdee 100644
--- a/pipes/memories/src/components/memories-gallery.tsx
+++ b/pipes/memories/src/components/memories-gallery.tsx
@@ -1,14 +1,17 @@
"use client";
-import { useState, useEffect } from "react";
+import { useState, useEffect, useRef } from "react";
import { motion } from "framer-motion";
-import { Play, Pause, Calendar } from "lucide-react";
+import { Play, Pause, Calendar, Loader2 } from "lucide-react";
import { format } from "date-fns";
import { Button } from "@/components/ui/button";
import { useToast } from "@/components/ui/use-toast";
import { pipe, ContentItem } from "@screenpipe/browser";
import { VideoComponent } from "@/components/video";
import { Skeleton } from "@/components/ui/skeleton";
+import { OpenAI } from "openai";
+import { generateId } from "ai";
+import { useSettings } from "@/lib/hooks/use-settings";
interface Memory {
id: string;
@@ -16,21 +19,37 @@ interface Memory {
preview_url: string;
duration: number;
app_name: string;
- title: string;
+ text: string;
+}
+
+interface VideoDescription {
+ id: string;
+ loading: boolean;
+ content: string;
}
export function MemoriesGallery() {
const [memories, setMemories] = useState<Memory[]>([]);
- const [playing, setPlaying] = useState<string | null>(null);
const { toast } = useToast();
const [isLoading, setIsLoading] = useState(true);
const [loadingMore, setLoadingMore] = useState(false);
+ const { settings } = useSettings();
+ const [videoDescriptions, setVideoDescriptions] = useState<{
+ [key: string]: VideoDescription;
+ }>({});
+ const abortControllerRef = useRef<AbortController | null>(null);
+ const [collectiveDescription, setCollectiveDescription] = useState<{
+ loading: boolean;
+ content: string;
+ }>({ loading: false, content: "" });
useEffect(() => {
fetchMemories();
}, []);
const fetchMemories = async (append = false) => {
+ // if (isLoading || loadingMore) return;
+
try {
if (append) {
setLoadingMore(true);
@@ -39,19 +58,27 @@ export function MemoriesGallery() {
}
const now = new Date();
+ const fiveMinutesAgo = new Date(now.getTime() - 5 * 60 * 1000);
const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
const targetCount = 6;
const uniqueMemories = new Set(memories.map((m) => m.id));
const newMemories: any[] = [];
+ const MAX_ATTEMPTS = 12; // 2x the target count
+ let totalAttempts = 0;
+
for (
let attempt = 0;
- attempt < targetCount * 4 && newMemories.length < targetCount;
+ attempt < targetCount * 2 &&
+ newMemories.length < targetCount &&
+ totalAttempts < MAX_ATTEMPTS;
attempt++
) {
+ totalAttempts++;
+
const randomTime = new Date(
thirtyDaysAgo.getTime() +
- Math.random() * (now.getTime() - thirtyDaysAgo.getTime())
+ Math.random() * (fiveMinutesAgo.getTime() - thirtyDaysAgo.getTime())
);
const response = await pipe.queryScreenpipe({
@@ -66,6 +93,14 @@ export function MemoriesGallery() {
).toISOString(),
});
+ console.log(
+ `attempt ${totalAttempts}: got ${response?.data?.length || 0} results`
+ );
+
+ if (!response?.data?.length) {
+ continue;
+ }
+
if (response?.data?.length) {
for (const item of response.data) {
// @ts-ignore
@@ -81,13 +116,21 @@ export function MemoriesGallery() {
// @ts-ignore
app_name: item.content.appName || "",
// @ts-ignore
- title: item.content.text.slice(0, 50) + "...",
+ text: item.content.text,
});
}
}
}
}
+ // If we didn't get enough memories, work with what we have
+ if (newMemories.length === 0) {
+ toast({
+ title: "note",
+ description: "no new memories found for this time period",
+ });
+ }
+
setMemories((prev) => (append ? [...prev, ...newMemories] : newMemories));
// Scroll to bottom if appending
@@ -111,6 +154,144 @@ export function MemoriesGallery() {
}
};
+ const generateVideoDescription = async (memory: Memory) => {
+ if (videoDescriptions[memory.id]) return;
+
+ const openai = new OpenAI({
+ apiKey:
+ settings.aiProviderType === "screenpipe-cloud"
+ ? settings.user.token
+ : settings.openaiApiKey,
+ baseURL: settings.aiUrl,
+ dangerouslyAllowBrowser: true,
+ });
+
+ setVideoDescriptions((prev) => ({
+ ...prev,
+ [memory.id]: {
+ id: generateId(),
+ loading: true,
+ content: "",
+ },
+ }));
+
+ try {
+ abortControllerRef.current = new AbortController();
+
+ const stream = await openai.chat.completions.create(
+ {
+ model: settings.aiModel,
+ messages: [
+ {
+ role: "system",
+ content:
+ "you are a helpful assistant that provides concise descriptions of OCR content from screen recordings. focus on key activities and content visible in the recording. you create short description of memories in less than 20 words.",
+ },
+ {
+ role: "user",
+ content: `describe this screen recording. app: ${memory.app_name}, text: ${memory.text}, duration: ${memory.duration}s`,
+ },
+ ],
+ stream: true,
+ },
+ {
+ signal: abortControllerRef.current.signal,
+ }
+ );
+
+ let fullResponse = "";
+
+ for await (const chunk of stream) {
+ const content = chunk.choices[0]?.delta?.content || "";
+ fullResponse += content;
+
+ setVideoDescriptions((prev) => ({
+ ...prev,
+ [memory.id]: {
+ ...prev[memory.id],
+ content: fullResponse,
+ },
+ }));
+ }
+ } catch (err) {
+ console.log("Failed to generate description:", err);
+ // toast({
+ // variant: "destructive",
+ // title: "error",
+ // description: "failed to generate video description",
+ // });
+ } finally {
+ setVideoDescriptions((prev) => ({
+ ...prev,
+ [memory.id]: {
+ ...prev[memory.id],
+ loading: false,
+ },
+ }));
+ }
+ };
+
+ const generateCollectiveDescription = async () => {
+ if (memories.length === 0) return;
+
+ setCollectiveDescription({ loading: true, content: "" });
+
+ try {
+ const openai = new OpenAI({
+ apiKey:
+ settings.aiProviderType === "screenpipe-cloud"
+ ? settings.user.token
+ : settings.openaiApiKey,
+ baseURL: settings.aiUrl,
+ dangerouslyAllowBrowser: true,
+ });
+
+ const memoryTexts = memories
+ .map(
+ (m) =>
+ `[${format(new Date(m.timestamp), "PPp")} - ${m.app_name}]: ${
+ m.text
+ }`
+ )
+ .join("\n");
+
+ const stream = await openai.chat.completions.create({
+ model: settings.aiModel,
+ messages: [
+ {
+ role: "system",
+ content:
+ "you are a helpful assistant that provides concise summaries of daily activities from screen recordings. create a brief narrative of what the person was doing across these memories in 2-3 sentences max. its a bunch of OCR'd screens, make something value packed and interesting.",
+ },
+ {
+ role: "user",
+ content: `summarize these screen recording contents:\n${memoryTexts}`,
+ },
+ ],
+ stream: true,
+ });
+
+ let fullResponse = "";
+ for await (const chunk of stream) {
+ const content = chunk.choices[0]?.delta?.content || "";
+ fullResponse += content;
+ setCollectiveDescription((prev) => ({
+ ...prev,
+ content: fullResponse,
+ }));
+ }
+ } catch (err) {
+ console.log("failed to generate collective description:", err);
+ toast({
+ variant: "destructive",
+ title: "error",
+ description: "failed to generate collective description",
+ });
+ } finally {
+ setCollectiveDescription((prev) => ({ ...prev, loading: false }));
+ }
+ };
+
return (
<div className="w-full max-w-7xl mx-auto p-4">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 max-w-6xl mx-auto">
@@ -140,10 +321,29 @@ export function MemoriesGallery() {
<VideoComponent
filePath={memory.preview_url}
className="w-full h-full"
+ onLoadStart={() => generateVideoDescription(memory)}
/>
- <div className="p-3 space-y-1 flex items-center justify-center">
- <Calendar className="h-3 w-3 mr-1" />
- {format(new Date(memory.timestamp), "PPp")}
+ <div className="p-3 space-y-1">
+ <div className="flex items-center justify-center">
+ <Calendar className="h-3 w-3 mr-1" />
+ {format(new Date(memory.timestamp), "PPp")}
+ </div>
+ {videoDescriptions[memory.id] && (
+ <motion.div
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ className="text-sm text-muted-foreground mt-2"
+ >
+ {videoDescriptions[memory.id].loading ? (
+ <div className="flex items-center justify-center">
+ <Loader2 className="h-3 w-3 animate-spin mr-2" />
+ generating description...
+ </div>
+ ) : (
+ videoDescriptions[memory.id].content
+ )}
+ </motion.div>
+ )}
</div>
</motion.div>
))}
@@ -168,6 +368,33 @@ export function MemoriesGallery() {
)}
</div>
+ <div className="mt-8 space-y-4">
+ <Button
+ className="mx-auto block"
+ onClick={generateCollectiveDescription}
+ disabled={isLoading || loadingMore || collectiveDescription.loading}
+ >
+ {collectiveDescription.loading ? (
+ <div className="flex items-center">
+ <Loader2 className="h-4 w-4 animate-spin mr-2" />
+ generating summary...
+ </div>
+ ) : (
+ "generate summary of visible memories"
+ )}
+ </Button>
+
+ {collectiveDescription.content && (
+ <motion.div
+ initial={{ opacity: 0, y: 10 }}
+ animate={{ opacity: 1, y: 0 }}
+ className="text-sm text-muted-foreground text-center max-w-2xl mx-auto p-4 rounded-lg border bg-background"
+ >
+ {collectiveDescription.content}
+ </motion.div>
+ )}
+ </div>
+
<Button
variant="outline"
className="mt-8 mx-auto block"
diff --git a/pipes/memories/src/components/video.tsx b/pipes/memories/src/components/video.tsx
index 581b417c4..d7cb67df9 100644
--- a/pipes/memories/src/components/video.tsx
+++ b/pipes/memories/src/components/video.tsx
@@ -8,12 +8,14 @@ export const VideoComponent = memo(function VideoComponent({
className,
startTime,
endTime,
+ onLoadStart,
}: {
filePath: string;
customDescription?: string;
className?: string;
startTime?: number;
endTime?: number;
+ onLoadStart?: () => void;
}) {
const [mediaSrc, setMediaSrc] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -31,7 +33,10 @@ export const VideoComponent = memo(function VideoComponent({
}, []);
const renderFileLink = () => (
- <div className="mt-2 text-center text-xs text-gray-500 truncate px-2" title={filePath}>
+ <div
+ className="mt-2 text-center text-xs text-gray-500 truncate px-2"
+ title={filePath}
+ >
{customDescription || filePath}
</div>
);
@@ -51,18 +56,34 @@ export const VideoComponent = memo(function VideoComponent({
}
};
+ const isMounted = useRef(true);
+
useEffect(() => {
+ return () => {
+ isMounted.current = false;
+ };
+ }, []);
+
+ useEffect(() => {
+ let isSubscribed = true;
+
async function loadMedia() {
try {
+ if (!mediaSrc && isSubscribed) {
+ onLoadStart?.();
+ }
+
const sanitizedPath = sanitizeFilePath(filePath);
- console.log("Sanitized path:", sanitizedPath);
- if (!sanitizedPath) {
- throw new Error("Invalid file path");
+ if (!sanitizedPath || !isSubscribed) {
+ return;
}
const validationStatus = await validateMedia(sanitizedPath);
- console.log("Media file:", validationStatus);
+
+ if (!isSubscribed) {
+ return;
+ }
if (validationStatus === "valid media file") {
setIsAudio(
@@ -76,37 +97,33 @@ export const VideoComponent = memo(function VideoComponent({
bytes[i] = binaryData.charCodeAt(i);
}
const blob = new Blob([bytes], { type: mimeType });
- setMediaSrc(URL.createObjectURL(blob));
- } else if (validationStatus.startsWith("media file does not exist")) {
- throw new Error(
- `${
- isAudio ? "audio" : "video"
- } file not exists, it might get deleted`
- );
- } else if (validationStatus.startsWith("invalid media file")) {
- throw new Error(
- `the ${
- isAudio ? "audio" : "video"
- } file is not written completely, please try again later`
- );
+ if (isSubscribed) {
+ setMediaSrc(URL.createObjectURL(blob));
+ }
} else {
- throw new Error("unknown media validation status");
+ throw new Error("Invalid media file");
}
} catch (error) {
- console.warn("Failed to load media:", error);
- setError(
- `Failed to load media: ${
- error instanceof Error ? error.message : "Unknown error"
- }`
- );
+ if (isSubscribed) {
+ console.warn("Failed to load media:", error);
+ setError(
+ `Failed to load media: ${
+ error instanceof Error ? error.message : "Unknown error"
+ }`
+ );
+ }
}
}
loadMedia();
+
return () => {
- if (mediaSrc) URL.revokeObjectURL(mediaSrc);
+ isSubscribed = false;
+ if (mediaSrc) {
+ URL.revokeObjectURL(mediaSrc);
+ }
};
- }, [filePath, sanitizeFilePath]);
+ }, [filePath, sanitizeFilePath, onLoadStart]);
if (error) {
return (